diff --git a/go.mod b/go.mod index c67efbcf..2004452c 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.19 require ( github.com/evanphx/json-patch v4.12.0+incompatible github.com/ghodss/yaml v1.0.0 + github.com/golang/mock v1.6.0 github.com/moby/locker v1.0.1 github.com/pkg/errors v0.9.1 github.com/rancher/lasso v0.0.0-20221227210133-6ea88ca2fbcc diff --git a/go.sum b/go.sum index c9162680..106e02c0 100644 --- a/go.sum +++ b/go.sum @@ -194,6 +194,7 @@ github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8= github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= +github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= @@ -805,6 +806,7 @@ golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= golang.org/x/tools v0.6.0 h1:BOw41kyTf3PuCW1pVQf8+Cyg8pMlkYB1oo9iJ6D/lKM= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= diff --git a/pkg/codegen/main.go b/pkg/codegen/main.go index b233485e..0bebe503 100644 --- a/pkg/codegen/main.go +++ b/pkg/codegen/main.go @@ -36,26 +36,17 @@ func main() { v1.PersistentVolumeClaim{}, v1.Pod{}, }, - InformersPackage: "k8s.io/client-go/informers", - ClientSetPackage: "k8s.io/client-go/kubernetes", - ListersPackage: "k8s.io/client-go/listers", }, discoveryv1.GroupName: { Types: []interface{}{ discoveryv1.EndpointSlice{}, }, OutputControllerPackageName: "discovery", - InformersPackage: "k8s.io/client-go/informers", - ClientSetPackage: "k8s.io/client-go/kubernetes", - ListersPackage: "k8s.io/client-go/listers", }, extensionsv1beta1.GroupName: { Types: []interface{}{ extensionsv1beta1.Ingress{}, }, - InformersPackage: "k8s.io/client-go/informers", - ClientSetPackage: "k8s.io/client-go/kubernetes", - ListersPackage: "k8s.io/client-go/listers", }, rbacv1.GroupName: { Types: []interface{}{ @@ -65,9 +56,6 @@ func main() { rbacv1.ClusterRoleBinding{}, }, OutputControllerPackageName: "rbac", - InformersPackage: "k8s.io/client-go/informers", - ClientSetPackage: "k8s.io/client-go/kubernetes", - ListersPackage: "k8s.io/client-go/listers", }, appsv1.GroupName: { Types: []interface{}{ @@ -75,67 +63,43 @@ func main() { appsv1.DaemonSet{}, appsv1.StatefulSet{}, }, - InformersPackage: "k8s.io/client-go/informers", - ClientSetPackage: "k8s.io/client-go/kubernetes", - ListersPackage: "k8s.io/client-go/listers", }, storagev1.GroupName: { OutputControllerPackageName: "storage", Types: []interface{}{ storagev1.StorageClass{}, }, - InformersPackage: "k8s.io/client-go/informers", - ClientSetPackage: "k8s.io/client-go/kubernetes", - ListersPackage: "k8s.io/client-go/listers", }, apiextv1.GroupName: { Types: []interface{}{ apiextv1.CustomResourceDefinition{}, }, - ClientSetPackage: "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset", - InformersPackage: "k8s.io/apiextensions-apiserver/pkg/client/informers/externalversions", - ListersPackage: "k8s.io/apiextensions-apiserver/pkg/client/listers", }, apiv1.GroupName: { Types: []interface{}{ apiv1.APIService{}, }, - ClientSetPackage: "k8s.io/kube-aggregator/pkg/client/clientset_generated/clientset", - InformersPackage: "k8s.io/kube-aggregator/pkg/client/informers/externalversions", - ListersPackage: "k8s.io/kube-aggregator/pkg/client/listers", }, batchv1.GroupName: { Types: []interface{}{ batchv1.Job{}, }, - InformersPackage: "k8s.io/client-go/informers", - ClientSetPackage: "k8s.io/client-go/kubernetes", - ListersPackage: "k8s.io/client-go/listers", }, networkingv1.GroupName: { Types: []interface{}{ networkingv1.NetworkPolicy{}, }, - InformersPackage: "k8s.io/client-go/informers", - ClientSetPackage: "k8s.io/client-go/kubernetes", - ListersPackage: "k8s.io/client-go/listers", }, admissionregistrationv1.GroupName: { Types: []interface{}{ admissionregistrationv1.ValidatingWebhookConfiguration{}, admissionregistrationv1.MutatingWebhookConfiguration{}, }, - InformersPackage: "k8s.io/client-go/informers", - ClientSetPackage: "k8s.io/client-go/kubernetes", - ListersPackage: "k8s.io/client-go/listers", }, coordinationv1.GroupName: { Types: []interface{}{ coordinationv1.Lease{}, }, - InformersPackage: "k8s.io/client-go/informers", - ClientSetPackage: "k8s.io/client-go/kubernetes", - ListersPackage: "k8s.io/client-go/listers", }, }, }) diff --git a/pkg/controller-gen/args/args.go b/pkg/controller-gen/args/args.go index f08fc528..95e5db69 100644 --- a/pkg/controller-gen/args/args.go +++ b/pkg/controller-gen/args/args.go @@ -40,8 +40,4 @@ type Group struct { GenerateInformers bool // The package name of the API types PackageName string - // Use existing clientset, informer, listers - ClientSetPackage string - ListersPackage string - InformersPackage string } diff --git a/pkg/controller-gen/generators/group_version_interface_go.go b/pkg/controller-gen/generators/group_version_interface_go.go index 1b2f806c..3d580fe5 100644 --- a/pkg/controller-gen/generators/group_version_interface_go.go +++ b/pkg/controller-gen/generators/group_version_interface_go.go @@ -90,10 +90,14 @@ func (f *groupInterfaceGo) Init(c *generator.Context, w io.Writer) error { "versionUpper": namer.IC(f.gv.Version), "groupUpper": upperLowercase(f.gv.Group), } - - sw.Do("func (c *version) {{.type}}() {{.type}}Controller {\n", m) - sw.Do("return New{{.type}}Controller(schema.GroupVersionKind{Group:\"{{.group}}\",Version:\"{{.version}}\",Kind:\"{{.type}}\"} , \"{{.pluralLower}}\", {{.namespaced}}, c.controllerFactory)\n", m) - sw.Do("}\n", m) + body := ` + func (v *version) {{.type}}() {{.type}}Controller { + return &{{.type}}GenericController { + generic.New{{ if not .namespaced}}NonNamespaced{{end}}Controller[*{{.version}}.{{.type}}, *{{.version}}.{{.type}}List](schema.GroupVersionKind{Group: "{{.group}}", Version: "{{.version}}", Kind: "{{.type}}"}, "{{.pluralLower}}", {{ if .namespaced}}true, {{end}}v.controllerFactory), + } + } + ` + sw.Do(body, m) } return sw.Error() diff --git a/pkg/controller-gen/generators/type_go.go b/pkg/controller-gen/generators/type_go.go index e6665daf..08da8e3d 100644 --- a/pkg/controller-gen/generators/type_go.go +++ b/pkg/controller-gen/generators/type_go.go @@ -82,234 +82,110 @@ func hasStatus(t *types.Type) bool { } var typeBody = ` -type {{.type}}Handler func(string, *{{.version}}.{{.type}}) (*{{.version}}.{{.type}}, error) - +// {{.type}}Controller interface for managing {{.type}} resources. type {{.type}}Controller interface { generic.ControllerMeta {{.type}}Client + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync {{.type}}Handler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync {{.type}}Handler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue({{ if .namespaced}}namespace, {{end}}name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter({{ if .namespaced}}namespace, {{end}}name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() {{.type}}Cache } +// {{.type}}Client interface for managing {{.type}} resources in Kubernetes. type {{.type}}Client interface { + // Create creates a new object and return the newly created Object or an error. Create(*{{.version}}.{{.type}}) (*{{.version}}.{{.type}}, error) + + // Update updates the object and return the newly updated Object or an error. Update(*{{.version}}.{{.type}}) (*{{.version}}.{{.type}}, error) {{ if .hasStatus -}} + + // UpdateStatus updates the Status field of a the object and return the newly updated Object or an error. + // Will always return an error if the object does not have a status field. UpdateStatus(*{{.version}}.{{.type}}) (*{{.version}}.{{.type}}, error) {{- end }} + + // Delete deletes the Object in the given name. Delete({{ if .namespaced}}namespace, {{end}}name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get({{ if .namespaced}}namespace, {{end}}name string, options metav1.GetOptions) (*{{.version}}.{{.type}}, error) + + // List will attempt to find multiple resources. List({{ if .namespaced}}namespace string, {{end}}opts metav1.ListOptions) (*{{.version}}.{{.type}}List, error) + + // Watch will start watching resources. Watch({{ if .namespaced}}namespace string, {{end}}opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch({{ if .namespaced}}namespace, {{end}}name string, pt types.PatchType, data []byte, subresources ...string) (result *{{.version}}.{{.type}}, err error) } +// {{.type}}Cache interface for retrieving {{.type}} resources in memory. type {{.type}}Cache interface { + // Get returns the resources with the specified name from the cache. Get({{ if .namespaced}}namespace, {{end}}name string) (*{{.version}}.{{.type}}, error) + + // List will attempt to find resources from the Cache. List({{ if .namespaced}}namespace string, {{end}}selector labels.Selector) ([]*{{.version}}.{{.type}}, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer {{.type}}Indexer) + + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. GetByIndex(indexName, key string) ([]*{{.version}}.{{.type}}, error) } +// {{.type}}Handler is function for performing any potential modifications to a {{.type}} resource. +type {{.type}}Handler func(string, *{{.version}}.{{.type}}) (*{{.version}}.{{.type}}, error) +// {{.type}}Indexer computes a set of indexed values for the provided object. type {{.type}}Indexer func(obj *{{.version}}.{{.type}}) ([]string, error) -type {{.lowerName}}Controller struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource +// {{.type}}GenericController wraps wrangler/pkg/generic.{{ if not .namespaced}}NonNamespaced{{end}}Controller so that the function definitions adhere to {{.type}}Controller interface. +type {{.type}}GenericController struct { + generic.{{ if not .namespaced}}NonNamespaced{{end}}ControllerInterface[*{{.version}}.{{.type}}, *{{.version}}.{{.type}}List] } -func New{{.type}}Controller(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) {{.type}}Controller { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &{{.lowerName}}Controller{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *{{.type}}GenericController) OnChange(ctx context.Context, name string, sync {{.type}}Handler) { + c.{{ if not .namespaced}}NonNamespaced{{end}}ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*{{.version}}.{{.type}}](sync)) } -func From{{.type}}HandlerToHandler(sync {{.type}}Handler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *{{.version}}.{{.type}} - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*{{.version}}.{{.type}})) - } - if v == nil { - return nil, err - } - return v, err - } +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *{{.type}}GenericController) OnRemove(ctx context.Context, name string, sync {{.type}}Handler) { + c.{{ if not .namespaced}}NonNamespaced{{end}}ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*{{.version}}.{{.type}}](sync)) } -func (c *{{.lowerName}}Controller) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*{{.version}}.{{.type}})) - if newObj == nil { - return nil, err - } - return newObj, err +// Cache returns a cache of resources in memory. +func (c *{{.type}}GenericController) Cache() {{.type}}Cache { + return &{{.type}}GenericCache{ + c.{{ if not .namespaced}}NonNamespaced{{end}}ControllerInterface.Cache(), } } -func Update{{.type}}DeepCopyOnChange(client {{.type}}Client, obj *{{.version}}.{{.type}}, handler func(obj *{{.version}}.{{.type}}) (*{{.version}}.{{.type}}, error)) (*{{.version}}.{{.type}}, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *{{.lowerName}}Controller) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} - -func (c *{{.lowerName}}Controller) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *{{.lowerName}}Controller) OnChange(ctx context.Context, name string, sync {{.type}}Handler) { - c.AddGenericHandler(ctx, name, From{{.type}}HandlerToHandler(sync)) +// {{.type}}GenericCache wraps wrangler/pkg/generic.{{ if not .namespaced}}NonNamespaced{{end}}Cache so the function definitions adhere to {{.type}}Cache interface. +type {{.type}}GenericCache struct { + generic.{{ if not .namespaced}}NonNamespaced{{end}}CacheInterface[*{{.version}}.{{.type}}] } -func (c *{{.lowerName}}Controller) OnRemove(ctx context.Context, name string, sync {{.type}}Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), From{{.type}}HandlerToHandler(sync))) -} - -func (c *{{.lowerName}}Controller) Enqueue({{ if .namespaced}}namespace, {{end}}name string) { - c.controller.Enqueue({{ if .namespaced }}namespace, {{else}}"", {{end}}name) -} - -func (c *{{.lowerName}}Controller) EnqueueAfter({{ if .namespaced}}namespace, {{end}}name string, duration time.Duration) { - c.controller.EnqueueAfter({{ if .namespaced }}namespace, {{else}}"", {{end}}name, duration) -} - -func (c *{{.lowerName}}Controller) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *{{.lowerName}}Controller) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *{{.lowerName}}Controller) Cache() {{.type}}Cache { - return &{{.lowerName}}Cache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *{{.lowerName}}Controller) Create(obj *{{.version}}.{{.type}}) (*{{.version}}.{{.type}}, error) { - result := &{{.version}}.{{.type}}{} - return result, c.client.Create(context.TODO(), {{ if .namespaced}}obj.Namespace,{{else}}"",{{end}} obj, result, metav1.CreateOptions{}) -} - -func (c *{{.lowerName}}Controller) Update(obj *{{.version}}.{{.type}}) (*{{.version}}.{{.type}}, error) { - result := &{{.version}}.{{.type}}{} - return result, c.client.Update(context.TODO(), {{ if .namespaced}}obj.Namespace,{{else}}"",{{end}} obj, result, metav1.UpdateOptions{}) -} - -{{ if .hasStatus -}} -func (c *{{.lowerName}}Controller) UpdateStatus(obj *{{.version}}.{{.type}}) (*{{.version}}.{{.type}}, error) { - result := &{{.version}}.{{.type}}{} - return result, c.client.UpdateStatus(context.TODO(), {{ if .namespaced}}obj.Namespace,{{else}}"",{{end}} obj, result, metav1.UpdateOptions{}) -} -{{- end }} - -func (c *{{.lowerName}}Controller) Delete({{ if .namespaced}}namespace, {{end}}name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), {{ if .namespaced}}namespace,{{else}}"",{{end}} name, *options) -} - -func (c *{{.lowerName}}Controller) Get({{ if .namespaced}}namespace, {{end}}name string, options metav1.GetOptions) (*{{.version}}.{{.type}}, error) { - result := &{{.version}}.{{.type}}{} - return result, c.client.Get(context.TODO(), {{ if .namespaced}}namespace,{{else}}"",{{end}} name, result, options) -} - -func (c *{{.lowerName}}Controller) List({{ if .namespaced}}namespace string, {{end}}opts metav1.ListOptions) (*{{.version}}.{{.type}}List, error) { - result := &{{.version}}.{{.type}}List{} - return result, c.client.List(context.TODO(), {{ if .namespaced}}namespace,{{else}}"",{{end}} result, opts) -} - -func (c *{{.lowerName}}Controller) Watch({{ if .namespaced}}namespace string, {{end}}opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), {{ if .namespaced}}namespace,{{else}}"",{{end}} opts) -} - -func (c *{{.lowerName}}Controller) Patch({{ if .namespaced}}namespace, {{end}}name string, pt types.PatchType, data []byte, subresources ...string) (*{{.version}}.{{.type}}, error) { - result := &{{.version}}.{{.type}}{} - return result, c.client.Patch(context.TODO(), {{ if .namespaced}}namespace,{{else}}"",{{end}} name, pt, data, result, metav1.PatchOptions{}, subresources...) -} - -type {{.lowerName}}Cache struct { - indexer cache.Indexer - resource schema.GroupResource -} - -func (c *{{.lowerName}}Cache) Get({{ if .namespaced}}namespace, {{end}}name string) (*{{.version}}.{{.type}}, error) { - obj, exists, err := c.indexer.GetByKey({{ if .namespaced }}namespace + "/" + {{end}}name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) - } - return obj.(*{{.version}}.{{.type}}), nil -} - -func (c *{{.lowerName}}Cache) List({{ if .namespaced}}namespace string, {{end}}selector labels.Selector) (ret []*{{.version}}.{{.type}}, err error) { - {{ if .namespaced }} - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*{{.version}}.{{.type}})) - }) - {{else}} - err = cache.ListAll(c.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*{{.version}}.{{.type}})) - }) - {{end}} - return ret, err -} - -func (c *{{.lowerName}}Cache) AddIndexer(indexName string, indexer {{.type}}Indexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*{{.version}}.{{.type}})) - }, - })) -} - -func (c *{{.lowerName}}Cache) GetByIndex(indexName, key string) (result []*{{.version}}.{{.type}}, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*{{.version}}.{{.type}}, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*{{.version}}.{{.type}})) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c {{.type}}GenericCache) AddIndexer(indexName string, indexer {{.type}}Indexer) { + c.{{ if not .namespaced}}NonNamespaced{{end}}CacheInterface.AddIndexer(indexName, generic.Indexer[*{{.version}}.{{.type}}](indexer)) } {{ if .hasStatus -}} @@ -317,6 +193,10 @@ type {{.type}}StatusHandler func(obj *{{.version}}.{{.type}}, status {{.version} type {{.type}}GeneratingHandler func(obj *{{.version}}.{{.type}}, status {{.version}}.{{.statusType}}) ([]runtime.Object, {{.version}}.{{.statusType}}, error) +func From{{.type}}HandlerToHandler(sync {{.type}}Handler) generic.Handler { + return generic.FromObjectHandlerToHandler(generic.ObjectHandler[*{{.version}}.{{.type}},](sync)) +} + func Register{{.type}}StatusHandler(ctx context.Context, controller {{.type}}Controller, condition condition.Cond, name string, handler {{.type}}StatusHandler) { statusHandler := &{{.lowerName}}StatusHandler{ client: controller, diff --git a/pkg/controller-gen/generators/util.go b/pkg/controller-gen/generators/util.go index 5458b079..f5c7193c 100644 --- a/pkg/controller-gen/generators/util.go +++ b/pkg/controller-gen/generators/util.go @@ -13,9 +13,8 @@ var ( "context", "time", "k8s.io/client-go/rest", - "github.com/rancher/lasso/pkg/client", - "github.com/rancher/lasso/pkg/controller", "github.com/rancher/wrangler/pkg/apply", + "github.com/rancher/lasso/pkg/controller", "github.com/rancher/wrangler/pkg/condition", "github.com/rancher/wrangler/pkg/schemes", "github.com/rancher/wrangler/pkg/generic", @@ -27,9 +26,7 @@ var ( "k8s.io/apimachinery/pkg/runtime", "k8s.io/apimachinery/pkg/runtime/schema", "k8s.io/apimachinery/pkg/types", - "utilruntime \"k8s.io/apimachinery/pkg/util/runtime\"", "k8s.io/apimachinery/pkg/watch", - "k8s.io/client-go/tools/cache", } ) diff --git a/pkg/controller-gen/main.go b/pkg/controller-gen/main.go index 731d7ea3..5cd2d4c9 100644 --- a/pkg/controller-gen/main.go +++ b/pkg/controller-gen/main.go @@ -352,15 +352,6 @@ func generateListers(groups map[string]bool, customArgs *cgargs.CustomArgs) erro func parseTypes(customArgs *cgargs.CustomArgs) []string { for groupName, group := range customArgs.Options.Groups { if group.GenerateTypes || group.GenerateClients { - if group.InformersPackage == "" { - group.InformersPackage = filepath.Join(customArgs.Package, "informers/externalversions") - } - if group.ClientSetPackage == "" { - group.ClientSetPackage = filepath.Join(customArgs.Package, "clientset/versioned") - } - if group.ListersPackage == "" { - group.ListersPackage = filepath.Join(customArgs.Package, "listers") - } customArgs.Options.Groups[groupName] = group } } diff --git a/pkg/generated/controllers/admissionregistration.k8s.io/v1/interface.go b/pkg/generated/controllers/admissionregistration.k8s.io/v1/interface.go index aa980103..d436f137 100644 --- a/pkg/generated/controllers/admissionregistration.k8s.io/v1/interface.go +++ b/pkg/generated/controllers/admissionregistration.k8s.io/v1/interface.go @@ -20,6 +20,7 @@ package v1 import ( "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/generic" "github.com/rancher/wrangler/pkg/schemes" v1 "k8s.io/api/admissionregistration/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -44,9 +45,14 @@ type version struct { controllerFactory controller.SharedControllerFactory } -func (c *version) MutatingWebhookConfiguration() MutatingWebhookConfigurationController { - return NewMutatingWebhookConfigurationController(schema.GroupVersionKind{Group: "admissionregistration.k8s.io", Version: "v1", Kind: "MutatingWebhookConfiguration"}, "mutatingwebhookconfigurations", false, c.controllerFactory) +func (v *version) MutatingWebhookConfiguration() MutatingWebhookConfigurationController { + return &MutatingWebhookConfigurationGenericController{ + generic.NewNonNamespacedController[*v1.MutatingWebhookConfiguration, *v1.MutatingWebhookConfigurationList](schema.GroupVersionKind{Group: "admissionregistration.k8s.io", Version: "v1", Kind: "MutatingWebhookConfiguration"}, "mutatingwebhookconfigurations", v.controllerFactory), + } } -func (c *version) ValidatingWebhookConfiguration() ValidatingWebhookConfigurationController { - return NewValidatingWebhookConfigurationController(schema.GroupVersionKind{Group: "admissionregistration.k8s.io", Version: "v1", Kind: "ValidatingWebhookConfiguration"}, "validatingwebhookconfigurations", false, c.controllerFactory) + +func (v *version) ValidatingWebhookConfiguration() ValidatingWebhookConfigurationController { + return &ValidatingWebhookConfigurationGenericController{ + generic.NewNonNamespacedController[*v1.ValidatingWebhookConfiguration, *v1.ValidatingWebhookConfigurationList](schema.GroupVersionKind{Group: "admissionregistration.k8s.io", Version: "v1", Kind: "ValidatingWebhookConfiguration"}, "validatingwebhookconfigurations", v.controllerFactory), + } } diff --git a/pkg/generated/controllers/admissionregistration.k8s.io/v1/mutatingwebhookconfiguration.go b/pkg/generated/controllers/admissionregistration.k8s.io/v1/mutatingwebhookconfiguration.go index 5da43d71..4482f48c 100644 --- a/pkg/generated/controllers/admissionregistration.k8s.io/v1/mutatingwebhookconfiguration.go +++ b/pkg/generated/controllers/admissionregistration.k8s.io/v1/mutatingwebhookconfiguration.go @@ -22,235 +22,111 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/admissionregistration/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type MutatingWebhookConfigurationHandler func(string, *v1.MutatingWebhookConfiguration) (*v1.MutatingWebhookConfiguration, error) - +// MutatingWebhookConfigurationController interface for managing MutatingWebhookConfiguration resources. type MutatingWebhookConfigurationController interface { generic.ControllerMeta MutatingWebhookConfigurationClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync MutatingWebhookConfigurationHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync MutatingWebhookConfigurationHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() MutatingWebhookConfigurationCache } +// MutatingWebhookConfigurationClient interface for managing MutatingWebhookConfiguration resources in Kubernetes. type MutatingWebhookConfigurationClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.MutatingWebhookConfiguration) (*v1.MutatingWebhookConfiguration, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.MutatingWebhookConfiguration) (*v1.MutatingWebhookConfiguration, error) + // Delete deletes the Object in the given name. Delete(name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(name string, options metav1.GetOptions) (*v1.MutatingWebhookConfiguration, error) + + // List will attempt to find multiple resources. List(opts metav1.ListOptions) (*v1.MutatingWebhookConfigurationList, error) + + // Watch will start watching resources. Watch(opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.MutatingWebhookConfiguration, err error) } +// MutatingWebhookConfigurationCache interface for retrieving MutatingWebhookConfiguration resources in memory. type MutatingWebhookConfigurationCache interface { + // Get returns the resources with the specified name from the cache. Get(name string) (*v1.MutatingWebhookConfiguration, error) + + // List will attempt to find resources from the Cache. List(selector labels.Selector) ([]*v1.MutatingWebhookConfiguration, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer MutatingWebhookConfigurationIndexer) - GetByIndex(indexName, key string) ([]*v1.MutatingWebhookConfiguration, error) -} - -type MutatingWebhookConfigurationIndexer func(obj *v1.MutatingWebhookConfiguration) ([]string, error) - -type mutatingWebhookConfigurationController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewMutatingWebhookConfigurationController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) MutatingWebhookConfigurationController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &mutatingWebhookConfigurationController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromMutatingWebhookConfigurationHandlerToHandler(sync MutatingWebhookConfigurationHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.MutatingWebhookConfiguration - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.MutatingWebhookConfiguration)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *mutatingWebhookConfigurationController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.MutatingWebhookConfiguration)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateMutatingWebhookConfigurationDeepCopyOnChange(client MutatingWebhookConfigurationClient, obj *v1.MutatingWebhookConfiguration, handler func(obj *v1.MutatingWebhookConfiguration) (*v1.MutatingWebhookConfiguration, error)) (*v1.MutatingWebhookConfiguration, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *mutatingWebhookConfigurationController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} -func (c *mutatingWebhookConfigurationController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *mutatingWebhookConfigurationController) OnChange(ctx context.Context, name string, sync MutatingWebhookConfigurationHandler) { - c.AddGenericHandler(ctx, name, FromMutatingWebhookConfigurationHandlerToHandler(sync)) -} - -func (c *mutatingWebhookConfigurationController) OnRemove(ctx context.Context, name string, sync MutatingWebhookConfigurationHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromMutatingWebhookConfigurationHandlerToHandler(sync))) -} - -func (c *mutatingWebhookConfigurationController) Enqueue(name string) { - c.controller.Enqueue("", name) -} - -func (c *mutatingWebhookConfigurationController) EnqueueAfter(name string, duration time.Duration) { - c.controller.EnqueueAfter("", name, duration) -} - -func (c *mutatingWebhookConfigurationController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *mutatingWebhookConfigurationController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *mutatingWebhookConfigurationController) Cache() MutatingWebhookConfigurationCache { - return &mutatingWebhookConfigurationCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *mutatingWebhookConfigurationController) Create(obj *v1.MutatingWebhookConfiguration) (*v1.MutatingWebhookConfiguration, error) { - result := &v1.MutatingWebhookConfiguration{} - return result, c.client.Create(context.TODO(), "", obj, result, metav1.CreateOptions{}) -} - -func (c *mutatingWebhookConfigurationController) Update(obj *v1.MutatingWebhookConfiguration) (*v1.MutatingWebhookConfiguration, error) { - result := &v1.MutatingWebhookConfiguration{} - return result, c.client.Update(context.TODO(), "", obj, result, metav1.UpdateOptions{}) -} - -func (c *mutatingWebhookConfigurationController) Delete(name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), "", name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.MutatingWebhookConfiguration, error) } -func (c *mutatingWebhookConfigurationController) Get(name string, options metav1.GetOptions) (*v1.MutatingWebhookConfiguration, error) { - result := &v1.MutatingWebhookConfiguration{} - return result, c.client.Get(context.TODO(), "", name, result, options) -} +// MutatingWebhookConfigurationHandler is function for performing any potential modifications to a MutatingWebhookConfiguration resource. +type MutatingWebhookConfigurationHandler func(string, *v1.MutatingWebhookConfiguration) (*v1.MutatingWebhookConfiguration, error) -func (c *mutatingWebhookConfigurationController) List(opts metav1.ListOptions) (*v1.MutatingWebhookConfigurationList, error) { - result := &v1.MutatingWebhookConfigurationList{} - return result, c.client.List(context.TODO(), "", result, opts) -} +// MutatingWebhookConfigurationIndexer computes a set of indexed values for the provided object. +type MutatingWebhookConfigurationIndexer func(obj *v1.MutatingWebhookConfiguration) ([]string, error) -func (c *mutatingWebhookConfigurationController) Watch(opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), "", opts) +// MutatingWebhookConfigurationGenericController wraps wrangler/pkg/generic.NonNamespacedController so that the function definitions adhere to MutatingWebhookConfigurationController interface. +type MutatingWebhookConfigurationGenericController struct { + generic.NonNamespacedControllerInterface[*v1.MutatingWebhookConfiguration, *v1.MutatingWebhookConfigurationList] } -func (c *mutatingWebhookConfigurationController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v1.MutatingWebhookConfiguration, error) { - result := &v1.MutatingWebhookConfiguration{} - return result, c.client.Patch(context.TODO(), "", name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *MutatingWebhookConfigurationGenericController) OnChange(ctx context.Context, name string, sync MutatingWebhookConfigurationHandler) { + c.NonNamespacedControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.MutatingWebhookConfiguration](sync)) } -type mutatingWebhookConfigurationCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *MutatingWebhookConfigurationGenericController) OnRemove(ctx context.Context, name string, sync MutatingWebhookConfigurationHandler) { + c.NonNamespacedControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.MutatingWebhookConfiguration](sync)) } -func (c *mutatingWebhookConfigurationCache) Get(name string) (*v1.MutatingWebhookConfiguration, error) { - obj, exists, err := c.indexer.GetByKey(name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *MutatingWebhookConfigurationGenericController) Cache() MutatingWebhookConfigurationCache { + return &MutatingWebhookConfigurationGenericCache{ + c.NonNamespacedControllerInterface.Cache(), } - return obj.(*v1.MutatingWebhookConfiguration), nil -} - -func (c *mutatingWebhookConfigurationCache) List(selector labels.Selector) (ret []*v1.MutatingWebhookConfiguration, err error) { - - err = cache.ListAll(c.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1.MutatingWebhookConfiguration)) - }) - - return ret, err } -func (c *mutatingWebhookConfigurationCache) AddIndexer(indexName string, indexer MutatingWebhookConfigurationIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.MutatingWebhookConfiguration)) - }, - })) +// MutatingWebhookConfigurationGenericCache wraps wrangler/pkg/generic.NonNamespacedCache so the function definitions adhere to MutatingWebhookConfigurationCache interface. +type MutatingWebhookConfigurationGenericCache struct { + generic.NonNamespacedCacheInterface[*v1.MutatingWebhookConfiguration] } -func (c *mutatingWebhookConfigurationCache) GetByIndex(indexName, key string) (result []*v1.MutatingWebhookConfiguration, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.MutatingWebhookConfiguration, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.MutatingWebhookConfiguration)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c MutatingWebhookConfigurationGenericCache) AddIndexer(indexName string, indexer MutatingWebhookConfigurationIndexer) { + c.NonNamespacedCacheInterface.AddIndexer(indexName, generic.Indexer[*v1.MutatingWebhookConfiguration](indexer)) } diff --git a/pkg/generated/controllers/admissionregistration.k8s.io/v1/validatingwebhookconfiguration.go b/pkg/generated/controllers/admissionregistration.k8s.io/v1/validatingwebhookconfiguration.go index 1d8aa044..cd44e9da 100644 --- a/pkg/generated/controllers/admissionregistration.k8s.io/v1/validatingwebhookconfiguration.go +++ b/pkg/generated/controllers/admissionregistration.k8s.io/v1/validatingwebhookconfiguration.go @@ -22,235 +22,111 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/admissionregistration/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type ValidatingWebhookConfigurationHandler func(string, *v1.ValidatingWebhookConfiguration) (*v1.ValidatingWebhookConfiguration, error) - +// ValidatingWebhookConfigurationController interface for managing ValidatingWebhookConfiguration resources. type ValidatingWebhookConfigurationController interface { generic.ControllerMeta ValidatingWebhookConfigurationClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync ValidatingWebhookConfigurationHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync ValidatingWebhookConfigurationHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() ValidatingWebhookConfigurationCache } +// ValidatingWebhookConfigurationClient interface for managing ValidatingWebhookConfiguration resources in Kubernetes. type ValidatingWebhookConfigurationClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.ValidatingWebhookConfiguration) (*v1.ValidatingWebhookConfiguration, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.ValidatingWebhookConfiguration) (*v1.ValidatingWebhookConfiguration, error) + // Delete deletes the Object in the given name. Delete(name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(name string, options metav1.GetOptions) (*v1.ValidatingWebhookConfiguration, error) + + // List will attempt to find multiple resources. List(opts metav1.ListOptions) (*v1.ValidatingWebhookConfigurationList, error) + + // Watch will start watching resources. Watch(opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.ValidatingWebhookConfiguration, err error) } +// ValidatingWebhookConfigurationCache interface for retrieving ValidatingWebhookConfiguration resources in memory. type ValidatingWebhookConfigurationCache interface { + // Get returns the resources with the specified name from the cache. Get(name string) (*v1.ValidatingWebhookConfiguration, error) + + // List will attempt to find resources from the Cache. List(selector labels.Selector) ([]*v1.ValidatingWebhookConfiguration, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer ValidatingWebhookConfigurationIndexer) - GetByIndex(indexName, key string) ([]*v1.ValidatingWebhookConfiguration, error) -} - -type ValidatingWebhookConfigurationIndexer func(obj *v1.ValidatingWebhookConfiguration) ([]string, error) - -type validatingWebhookConfigurationController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewValidatingWebhookConfigurationController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) ValidatingWebhookConfigurationController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &validatingWebhookConfigurationController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromValidatingWebhookConfigurationHandlerToHandler(sync ValidatingWebhookConfigurationHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.ValidatingWebhookConfiguration - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.ValidatingWebhookConfiguration)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *validatingWebhookConfigurationController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.ValidatingWebhookConfiguration)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateValidatingWebhookConfigurationDeepCopyOnChange(client ValidatingWebhookConfigurationClient, obj *v1.ValidatingWebhookConfiguration, handler func(obj *v1.ValidatingWebhookConfiguration) (*v1.ValidatingWebhookConfiguration, error)) (*v1.ValidatingWebhookConfiguration, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *validatingWebhookConfigurationController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} -func (c *validatingWebhookConfigurationController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *validatingWebhookConfigurationController) OnChange(ctx context.Context, name string, sync ValidatingWebhookConfigurationHandler) { - c.AddGenericHandler(ctx, name, FromValidatingWebhookConfigurationHandlerToHandler(sync)) -} - -func (c *validatingWebhookConfigurationController) OnRemove(ctx context.Context, name string, sync ValidatingWebhookConfigurationHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromValidatingWebhookConfigurationHandlerToHandler(sync))) -} - -func (c *validatingWebhookConfigurationController) Enqueue(name string) { - c.controller.Enqueue("", name) -} - -func (c *validatingWebhookConfigurationController) EnqueueAfter(name string, duration time.Duration) { - c.controller.EnqueueAfter("", name, duration) -} - -func (c *validatingWebhookConfigurationController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *validatingWebhookConfigurationController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *validatingWebhookConfigurationController) Cache() ValidatingWebhookConfigurationCache { - return &validatingWebhookConfigurationCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *validatingWebhookConfigurationController) Create(obj *v1.ValidatingWebhookConfiguration) (*v1.ValidatingWebhookConfiguration, error) { - result := &v1.ValidatingWebhookConfiguration{} - return result, c.client.Create(context.TODO(), "", obj, result, metav1.CreateOptions{}) -} - -func (c *validatingWebhookConfigurationController) Update(obj *v1.ValidatingWebhookConfiguration) (*v1.ValidatingWebhookConfiguration, error) { - result := &v1.ValidatingWebhookConfiguration{} - return result, c.client.Update(context.TODO(), "", obj, result, metav1.UpdateOptions{}) -} - -func (c *validatingWebhookConfigurationController) Delete(name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), "", name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.ValidatingWebhookConfiguration, error) } -func (c *validatingWebhookConfigurationController) Get(name string, options metav1.GetOptions) (*v1.ValidatingWebhookConfiguration, error) { - result := &v1.ValidatingWebhookConfiguration{} - return result, c.client.Get(context.TODO(), "", name, result, options) -} +// ValidatingWebhookConfigurationHandler is function for performing any potential modifications to a ValidatingWebhookConfiguration resource. +type ValidatingWebhookConfigurationHandler func(string, *v1.ValidatingWebhookConfiguration) (*v1.ValidatingWebhookConfiguration, error) -func (c *validatingWebhookConfigurationController) List(opts metav1.ListOptions) (*v1.ValidatingWebhookConfigurationList, error) { - result := &v1.ValidatingWebhookConfigurationList{} - return result, c.client.List(context.TODO(), "", result, opts) -} +// ValidatingWebhookConfigurationIndexer computes a set of indexed values for the provided object. +type ValidatingWebhookConfigurationIndexer func(obj *v1.ValidatingWebhookConfiguration) ([]string, error) -func (c *validatingWebhookConfigurationController) Watch(opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), "", opts) +// ValidatingWebhookConfigurationGenericController wraps wrangler/pkg/generic.NonNamespacedController so that the function definitions adhere to ValidatingWebhookConfigurationController interface. +type ValidatingWebhookConfigurationGenericController struct { + generic.NonNamespacedControllerInterface[*v1.ValidatingWebhookConfiguration, *v1.ValidatingWebhookConfigurationList] } -func (c *validatingWebhookConfigurationController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v1.ValidatingWebhookConfiguration, error) { - result := &v1.ValidatingWebhookConfiguration{} - return result, c.client.Patch(context.TODO(), "", name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *ValidatingWebhookConfigurationGenericController) OnChange(ctx context.Context, name string, sync ValidatingWebhookConfigurationHandler) { + c.NonNamespacedControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.ValidatingWebhookConfiguration](sync)) } -type validatingWebhookConfigurationCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *ValidatingWebhookConfigurationGenericController) OnRemove(ctx context.Context, name string, sync ValidatingWebhookConfigurationHandler) { + c.NonNamespacedControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.ValidatingWebhookConfiguration](sync)) } -func (c *validatingWebhookConfigurationCache) Get(name string) (*v1.ValidatingWebhookConfiguration, error) { - obj, exists, err := c.indexer.GetByKey(name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *ValidatingWebhookConfigurationGenericController) Cache() ValidatingWebhookConfigurationCache { + return &ValidatingWebhookConfigurationGenericCache{ + c.NonNamespacedControllerInterface.Cache(), } - return obj.(*v1.ValidatingWebhookConfiguration), nil -} - -func (c *validatingWebhookConfigurationCache) List(selector labels.Selector) (ret []*v1.ValidatingWebhookConfiguration, err error) { - - err = cache.ListAll(c.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1.ValidatingWebhookConfiguration)) - }) - - return ret, err } -func (c *validatingWebhookConfigurationCache) AddIndexer(indexName string, indexer ValidatingWebhookConfigurationIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.ValidatingWebhookConfiguration)) - }, - })) +// ValidatingWebhookConfigurationGenericCache wraps wrangler/pkg/generic.NonNamespacedCache so the function definitions adhere to ValidatingWebhookConfigurationCache interface. +type ValidatingWebhookConfigurationGenericCache struct { + generic.NonNamespacedCacheInterface[*v1.ValidatingWebhookConfiguration] } -func (c *validatingWebhookConfigurationCache) GetByIndex(indexName, key string) (result []*v1.ValidatingWebhookConfiguration, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.ValidatingWebhookConfiguration, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.ValidatingWebhookConfiguration)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c ValidatingWebhookConfigurationGenericCache) AddIndexer(indexName string, indexer ValidatingWebhookConfigurationIndexer) { + c.NonNamespacedCacheInterface.AddIndexer(indexName, generic.Indexer[*v1.ValidatingWebhookConfiguration](indexer)) } diff --git a/pkg/generated/controllers/apiextensions.k8s.io/v1/customresourcedefinition.go b/pkg/generated/controllers/apiextensions.k8s.io/v1/customresourcedefinition.go index be7526f8..15cf29d1 100644 --- a/pkg/generated/controllers/apiextensions.k8s.io/v1/customresourcedefinition.go +++ b/pkg/generated/controllers/apiextensions.k8s.io/v1/customresourcedefinition.go @@ -22,8 +22,6 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,237 +34,121 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type CustomResourceDefinitionHandler func(string, *v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error) - +// CustomResourceDefinitionController interface for managing CustomResourceDefinition resources. type CustomResourceDefinitionController interface { generic.ControllerMeta CustomResourceDefinitionClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync CustomResourceDefinitionHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync CustomResourceDefinitionHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() CustomResourceDefinitionCache } +// CustomResourceDefinitionClient interface for managing CustomResourceDefinition resources in Kubernetes. type CustomResourceDefinitionClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error) + // UpdateStatus updates the Status field of a the object and return the newly updated Object or an error. + // Will always return an error if the object does not have a status field. UpdateStatus(*v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error) + + // Delete deletes the Object in the given name. Delete(name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(name string, options metav1.GetOptions) (*v1.CustomResourceDefinition, error) + + // List will attempt to find multiple resources. List(opts metav1.ListOptions) (*v1.CustomResourceDefinitionList, error) + + // Watch will start watching resources. Watch(opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.CustomResourceDefinition, err error) } +// CustomResourceDefinitionCache interface for retrieving CustomResourceDefinition resources in memory. type CustomResourceDefinitionCache interface { + // Get returns the resources with the specified name from the cache. Get(name string) (*v1.CustomResourceDefinition, error) + + // List will attempt to find resources from the Cache. List(selector labels.Selector) ([]*v1.CustomResourceDefinition, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer CustomResourceDefinitionIndexer) - GetByIndex(indexName, key string) ([]*v1.CustomResourceDefinition, error) -} - -type CustomResourceDefinitionIndexer func(obj *v1.CustomResourceDefinition) ([]string, error) - -type customResourceDefinitionController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewCustomResourceDefinitionController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) CustomResourceDefinitionController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &customResourceDefinitionController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromCustomResourceDefinitionHandlerToHandler(sync CustomResourceDefinitionHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.CustomResourceDefinition - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.CustomResourceDefinition)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *customResourceDefinitionController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.CustomResourceDefinition)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateCustomResourceDefinitionDeepCopyOnChange(client CustomResourceDefinitionClient, obj *v1.CustomResourceDefinition, handler func(obj *v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error)) (*v1.CustomResourceDefinition, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *customResourceDefinitionController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} - -func (c *customResourceDefinitionController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *customResourceDefinitionController) OnChange(ctx context.Context, name string, sync CustomResourceDefinitionHandler) { - c.AddGenericHandler(ctx, name, FromCustomResourceDefinitionHandlerToHandler(sync)) -} - -func (c *customResourceDefinitionController) OnRemove(ctx context.Context, name string, sync CustomResourceDefinitionHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromCustomResourceDefinitionHandlerToHandler(sync))) -} - -func (c *customResourceDefinitionController) Enqueue(name string) { - c.controller.Enqueue("", name) -} - -func (c *customResourceDefinitionController) EnqueueAfter(name string, duration time.Duration) { - c.controller.EnqueueAfter("", name, duration) -} - -func (c *customResourceDefinitionController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *customResourceDefinitionController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *customResourceDefinitionController) Cache() CustomResourceDefinitionCache { - return &customResourceDefinitionCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *customResourceDefinitionController) Create(obj *v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error) { - result := &v1.CustomResourceDefinition{} - return result, c.client.Create(context.TODO(), "", obj, result, metav1.CreateOptions{}) -} - -func (c *customResourceDefinitionController) Update(obj *v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error) { - result := &v1.CustomResourceDefinition{} - return result, c.client.Update(context.TODO(), "", obj, result, metav1.UpdateOptions{}) -} - -func (c *customResourceDefinitionController) UpdateStatus(obj *v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error) { - result := &v1.CustomResourceDefinition{} - return result, c.client.UpdateStatus(context.TODO(), "", obj, result, metav1.UpdateOptions{}) -} -func (c *customResourceDefinitionController) Delete(name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), "", name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.CustomResourceDefinition, error) } -func (c *customResourceDefinitionController) Get(name string, options metav1.GetOptions) (*v1.CustomResourceDefinition, error) { - result := &v1.CustomResourceDefinition{} - return result, c.client.Get(context.TODO(), "", name, result, options) -} +// CustomResourceDefinitionHandler is function for performing any potential modifications to a CustomResourceDefinition resource. +type CustomResourceDefinitionHandler func(string, *v1.CustomResourceDefinition) (*v1.CustomResourceDefinition, error) -func (c *customResourceDefinitionController) List(opts metav1.ListOptions) (*v1.CustomResourceDefinitionList, error) { - result := &v1.CustomResourceDefinitionList{} - return result, c.client.List(context.TODO(), "", result, opts) -} +// CustomResourceDefinitionIndexer computes a set of indexed values for the provided object. +type CustomResourceDefinitionIndexer func(obj *v1.CustomResourceDefinition) ([]string, error) -func (c *customResourceDefinitionController) Watch(opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), "", opts) +// CustomResourceDefinitionGenericController wraps wrangler/pkg/generic.NonNamespacedController so that the function definitions adhere to CustomResourceDefinitionController interface. +type CustomResourceDefinitionGenericController struct { + generic.NonNamespacedControllerInterface[*v1.CustomResourceDefinition, *v1.CustomResourceDefinitionList] } -func (c *customResourceDefinitionController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v1.CustomResourceDefinition, error) { - result := &v1.CustomResourceDefinition{} - return result, c.client.Patch(context.TODO(), "", name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *CustomResourceDefinitionGenericController) OnChange(ctx context.Context, name string, sync CustomResourceDefinitionHandler) { + c.NonNamespacedControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.CustomResourceDefinition](sync)) } -type customResourceDefinitionCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *CustomResourceDefinitionGenericController) OnRemove(ctx context.Context, name string, sync CustomResourceDefinitionHandler) { + c.NonNamespacedControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.CustomResourceDefinition](sync)) } -func (c *customResourceDefinitionCache) Get(name string) (*v1.CustomResourceDefinition, error) { - obj, exists, err := c.indexer.GetByKey(name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *CustomResourceDefinitionGenericController) Cache() CustomResourceDefinitionCache { + return &CustomResourceDefinitionGenericCache{ + c.NonNamespacedControllerInterface.Cache(), } - return obj.(*v1.CustomResourceDefinition), nil } -func (c *customResourceDefinitionCache) List(selector labels.Selector) (ret []*v1.CustomResourceDefinition, err error) { - - err = cache.ListAll(c.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1.CustomResourceDefinition)) - }) - - return ret, err +// CustomResourceDefinitionGenericCache wraps wrangler/pkg/generic.NonNamespacedCache so the function definitions adhere to CustomResourceDefinitionCache interface. +type CustomResourceDefinitionGenericCache struct { + generic.NonNamespacedCacheInterface[*v1.CustomResourceDefinition] } -func (c *customResourceDefinitionCache) AddIndexer(indexName string, indexer CustomResourceDefinitionIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.CustomResourceDefinition)) - }, - })) -} - -func (c *customResourceDefinitionCache) GetByIndex(indexName, key string) (result []*v1.CustomResourceDefinition, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.CustomResourceDefinition, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.CustomResourceDefinition)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c CustomResourceDefinitionGenericCache) AddIndexer(indexName string, indexer CustomResourceDefinitionIndexer) { + c.NonNamespacedCacheInterface.AddIndexer(indexName, generic.Indexer[*v1.CustomResourceDefinition](indexer)) } type CustomResourceDefinitionStatusHandler func(obj *v1.CustomResourceDefinition, status v1.CustomResourceDefinitionStatus) (v1.CustomResourceDefinitionStatus, error) type CustomResourceDefinitionGeneratingHandler func(obj *v1.CustomResourceDefinition, status v1.CustomResourceDefinitionStatus) ([]runtime.Object, v1.CustomResourceDefinitionStatus, error) +func FromCustomResourceDefinitionHandlerToHandler(sync CustomResourceDefinitionHandler) generic.Handler { + return generic.FromObjectHandlerToHandler(generic.ObjectHandler[*v1.CustomResourceDefinition](sync)) +} + func RegisterCustomResourceDefinitionStatusHandler(ctx context.Context, controller CustomResourceDefinitionController, condition condition.Cond, name string, handler CustomResourceDefinitionStatusHandler) { statusHandler := &customResourceDefinitionStatusHandler{ client: controller, diff --git a/pkg/generated/controllers/apiextensions.k8s.io/v1/interface.go b/pkg/generated/controllers/apiextensions.k8s.io/v1/interface.go index ba505b6b..4f1c3c9b 100644 --- a/pkg/generated/controllers/apiextensions.k8s.io/v1/interface.go +++ b/pkg/generated/controllers/apiextensions.k8s.io/v1/interface.go @@ -20,6 +20,7 @@ package v1 import ( "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/generic" "github.com/rancher/wrangler/pkg/schemes" v1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -43,6 +44,8 @@ type version struct { controllerFactory controller.SharedControllerFactory } -func (c *version) CustomResourceDefinition() CustomResourceDefinitionController { - return NewCustomResourceDefinitionController(schema.GroupVersionKind{Group: "apiextensions.k8s.io", Version: "v1", Kind: "CustomResourceDefinition"}, "customresourcedefinitions", false, c.controllerFactory) +func (v *version) CustomResourceDefinition() CustomResourceDefinitionController { + return &CustomResourceDefinitionGenericController{ + generic.NewNonNamespacedController[*v1.CustomResourceDefinition, *v1.CustomResourceDefinitionList](schema.GroupVersionKind{Group: "apiextensions.k8s.io", Version: "v1", Kind: "CustomResourceDefinition"}, "customresourcedefinitions", v.controllerFactory), + } } diff --git a/pkg/generated/controllers/apiregistration.k8s.io/v1/apiservice.go b/pkg/generated/controllers/apiregistration.k8s.io/v1/apiservice.go index 35dbaa1b..2bab06b8 100644 --- a/pkg/generated/controllers/apiregistration.k8s.io/v1/apiservice.go +++ b/pkg/generated/controllers/apiregistration.k8s.io/v1/apiservice.go @@ -22,8 +22,6 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -35,238 +33,122 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" v1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1" ) -type APIServiceHandler func(string, *v1.APIService) (*v1.APIService, error) - +// APIServiceController interface for managing APIService resources. type APIServiceController interface { generic.ControllerMeta APIServiceClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync APIServiceHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync APIServiceHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() APIServiceCache } +// APIServiceClient interface for managing APIService resources in Kubernetes. type APIServiceClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.APIService) (*v1.APIService, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.APIService) (*v1.APIService, error) + // UpdateStatus updates the Status field of a the object and return the newly updated Object or an error. + // Will always return an error if the object does not have a status field. UpdateStatus(*v1.APIService) (*v1.APIService, error) + + // Delete deletes the Object in the given name. Delete(name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(name string, options metav1.GetOptions) (*v1.APIService, error) + + // List will attempt to find multiple resources. List(opts metav1.ListOptions) (*v1.APIServiceList, error) + + // Watch will start watching resources. Watch(opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.APIService, err error) } +// APIServiceCache interface for retrieving APIService resources in memory. type APIServiceCache interface { + // Get returns the resources with the specified name from the cache. Get(name string) (*v1.APIService, error) + + // List will attempt to find resources from the Cache. List(selector labels.Selector) ([]*v1.APIService, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer APIServiceIndexer) - GetByIndex(indexName, key string) ([]*v1.APIService, error) -} - -type APIServiceIndexer func(obj *v1.APIService) ([]string, error) - -type aPIServiceController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewAPIServiceController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) APIServiceController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &aPIServiceController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromAPIServiceHandlerToHandler(sync APIServiceHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.APIService - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.APIService)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *aPIServiceController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.APIService)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateAPIServiceDeepCopyOnChange(client APIServiceClient, obj *v1.APIService, handler func(obj *v1.APIService) (*v1.APIService, error)) (*v1.APIService, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *aPIServiceController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} - -func (c *aPIServiceController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *aPIServiceController) OnChange(ctx context.Context, name string, sync APIServiceHandler) { - c.AddGenericHandler(ctx, name, FromAPIServiceHandlerToHandler(sync)) -} - -func (c *aPIServiceController) OnRemove(ctx context.Context, name string, sync APIServiceHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromAPIServiceHandlerToHandler(sync))) -} - -func (c *aPIServiceController) Enqueue(name string) { - c.controller.Enqueue("", name) -} - -func (c *aPIServiceController) EnqueueAfter(name string, duration time.Duration) { - c.controller.EnqueueAfter("", name, duration) -} - -func (c *aPIServiceController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *aPIServiceController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *aPIServiceController) Cache() APIServiceCache { - return &aPIServiceCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *aPIServiceController) Create(obj *v1.APIService) (*v1.APIService, error) { - result := &v1.APIService{} - return result, c.client.Create(context.TODO(), "", obj, result, metav1.CreateOptions{}) -} - -func (c *aPIServiceController) Update(obj *v1.APIService) (*v1.APIService, error) { - result := &v1.APIService{} - return result, c.client.Update(context.TODO(), "", obj, result, metav1.UpdateOptions{}) -} - -func (c *aPIServiceController) UpdateStatus(obj *v1.APIService) (*v1.APIService, error) { - result := &v1.APIService{} - return result, c.client.UpdateStatus(context.TODO(), "", obj, result, metav1.UpdateOptions{}) -} -func (c *aPIServiceController) Delete(name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), "", name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.APIService, error) } -func (c *aPIServiceController) Get(name string, options metav1.GetOptions) (*v1.APIService, error) { - result := &v1.APIService{} - return result, c.client.Get(context.TODO(), "", name, result, options) -} +// APIServiceHandler is function for performing any potential modifications to a APIService resource. +type APIServiceHandler func(string, *v1.APIService) (*v1.APIService, error) -func (c *aPIServiceController) List(opts metav1.ListOptions) (*v1.APIServiceList, error) { - result := &v1.APIServiceList{} - return result, c.client.List(context.TODO(), "", result, opts) -} +// APIServiceIndexer computes a set of indexed values for the provided object. +type APIServiceIndexer func(obj *v1.APIService) ([]string, error) -func (c *aPIServiceController) Watch(opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), "", opts) +// APIServiceGenericController wraps wrangler/pkg/generic.NonNamespacedController so that the function definitions adhere to APIServiceController interface. +type APIServiceGenericController struct { + generic.NonNamespacedControllerInterface[*v1.APIService, *v1.APIServiceList] } -func (c *aPIServiceController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v1.APIService, error) { - result := &v1.APIService{} - return result, c.client.Patch(context.TODO(), "", name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *APIServiceGenericController) OnChange(ctx context.Context, name string, sync APIServiceHandler) { + c.NonNamespacedControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.APIService](sync)) } -type aPIServiceCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *APIServiceGenericController) OnRemove(ctx context.Context, name string, sync APIServiceHandler) { + c.NonNamespacedControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.APIService](sync)) } -func (c *aPIServiceCache) Get(name string) (*v1.APIService, error) { - obj, exists, err := c.indexer.GetByKey(name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *APIServiceGenericController) Cache() APIServiceCache { + return &APIServiceGenericCache{ + c.NonNamespacedControllerInterface.Cache(), } - return obj.(*v1.APIService), nil } -func (c *aPIServiceCache) List(selector labels.Selector) (ret []*v1.APIService, err error) { - - err = cache.ListAll(c.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1.APIService)) - }) - - return ret, err +// APIServiceGenericCache wraps wrangler/pkg/generic.NonNamespacedCache so the function definitions adhere to APIServiceCache interface. +type APIServiceGenericCache struct { + generic.NonNamespacedCacheInterface[*v1.APIService] } -func (c *aPIServiceCache) AddIndexer(indexName string, indexer APIServiceIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.APIService)) - }, - })) -} - -func (c *aPIServiceCache) GetByIndex(indexName, key string) (result []*v1.APIService, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.APIService, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.APIService)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c APIServiceGenericCache) AddIndexer(indexName string, indexer APIServiceIndexer) { + c.NonNamespacedCacheInterface.AddIndexer(indexName, generic.Indexer[*v1.APIService](indexer)) } type APIServiceStatusHandler func(obj *v1.APIService, status v1.APIServiceStatus) (v1.APIServiceStatus, error) type APIServiceGeneratingHandler func(obj *v1.APIService, status v1.APIServiceStatus) ([]runtime.Object, v1.APIServiceStatus, error) +func FromAPIServiceHandlerToHandler(sync APIServiceHandler) generic.Handler { + return generic.FromObjectHandlerToHandler(generic.ObjectHandler[*v1.APIService](sync)) +} + func RegisterAPIServiceStatusHandler(ctx context.Context, controller APIServiceController, condition condition.Cond, name string, handler APIServiceStatusHandler) { statusHandler := &aPIServiceStatusHandler{ client: controller, diff --git a/pkg/generated/controllers/apiregistration.k8s.io/v1/interface.go b/pkg/generated/controllers/apiregistration.k8s.io/v1/interface.go index cfb21076..29d1f251 100644 --- a/pkg/generated/controllers/apiregistration.k8s.io/v1/interface.go +++ b/pkg/generated/controllers/apiregistration.k8s.io/v1/interface.go @@ -20,6 +20,7 @@ package v1 import ( "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/generic" "github.com/rancher/wrangler/pkg/schemes" "k8s.io/apimachinery/pkg/runtime/schema" v1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1" @@ -43,6 +44,8 @@ type version struct { controllerFactory controller.SharedControllerFactory } -func (c *version) APIService() APIServiceController { - return NewAPIServiceController(schema.GroupVersionKind{Group: "apiregistration.k8s.io", Version: "v1", Kind: "APIService"}, "apiservices", false, c.controllerFactory) +func (v *version) APIService() APIServiceController { + return &APIServiceGenericController{ + generic.NewNonNamespacedController[*v1.APIService, *v1.APIServiceList](schema.GroupVersionKind{Group: "apiregistration.k8s.io", Version: "v1", Kind: "APIService"}, "apiservices", v.controllerFactory), + } } diff --git a/pkg/generated/controllers/apps/v1/daemonset.go b/pkg/generated/controllers/apps/v1/daemonset.go index 039d680d..0d8d86ff 100644 --- a/pkg/generated/controllers/apps/v1/daemonset.go +++ b/pkg/generated/controllers/apps/v1/daemonset.go @@ -22,8 +22,6 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,237 +34,121 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type DaemonSetHandler func(string, *v1.DaemonSet) (*v1.DaemonSet, error) - +// DaemonSetController interface for managing DaemonSet resources. type DaemonSetController interface { generic.ControllerMeta DaemonSetClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync DaemonSetHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync DaemonSetHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(namespace, name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() DaemonSetCache } +// DaemonSetClient interface for managing DaemonSet resources in Kubernetes. type DaemonSetClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.DaemonSet) (*v1.DaemonSet, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.DaemonSet) (*v1.DaemonSet, error) + // UpdateStatus updates the Status field of a the object and return the newly updated Object or an error. + // Will always return an error if the object does not have a status field. UpdateStatus(*v1.DaemonSet) (*v1.DaemonSet, error) + + // Delete deletes the Object in the given name. Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(namespace, name string, options metav1.GetOptions) (*v1.DaemonSet, error) + + // List will attempt to find multiple resources. List(namespace string, opts metav1.ListOptions) (*v1.DaemonSetList, error) + + // Watch will start watching resources. Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.DaemonSet, err error) } +// DaemonSetCache interface for retrieving DaemonSet resources in memory. type DaemonSetCache interface { + // Get returns the resources with the specified name from the cache. Get(namespace, name string) (*v1.DaemonSet, error) + + // List will attempt to find resources from the Cache. List(namespace string, selector labels.Selector) ([]*v1.DaemonSet, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer DaemonSetIndexer) - GetByIndex(indexName, key string) ([]*v1.DaemonSet, error) -} - -type DaemonSetIndexer func(obj *v1.DaemonSet) ([]string, error) - -type daemonSetController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewDaemonSetController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) DaemonSetController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &daemonSetController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromDaemonSetHandlerToHandler(sync DaemonSetHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.DaemonSet - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.DaemonSet)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *daemonSetController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.DaemonSet)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateDaemonSetDeepCopyOnChange(client DaemonSetClient, obj *v1.DaemonSet, handler func(obj *v1.DaemonSet) (*v1.DaemonSet, error)) (*v1.DaemonSet, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *daemonSetController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} - -func (c *daemonSetController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *daemonSetController) OnChange(ctx context.Context, name string, sync DaemonSetHandler) { - c.AddGenericHandler(ctx, name, FromDaemonSetHandlerToHandler(sync)) -} - -func (c *daemonSetController) OnRemove(ctx context.Context, name string, sync DaemonSetHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromDaemonSetHandlerToHandler(sync))) -} - -func (c *daemonSetController) Enqueue(namespace, name string) { - c.controller.Enqueue(namespace, name) -} - -func (c *daemonSetController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controller.EnqueueAfter(namespace, name, duration) -} - -func (c *daemonSetController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *daemonSetController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *daemonSetController) Cache() DaemonSetCache { - return &daemonSetCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *daemonSetController) Create(obj *v1.DaemonSet) (*v1.DaemonSet, error) { - result := &v1.DaemonSet{} - return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) -} - -func (c *daemonSetController) Update(obj *v1.DaemonSet) (*v1.DaemonSet, error) { - result := &v1.DaemonSet{} - return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} - -func (c *daemonSetController) UpdateStatus(obj *v1.DaemonSet) (*v1.DaemonSet, error) { - result := &v1.DaemonSet{} - return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} -func (c *daemonSetController) Delete(namespace, name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), namespace, name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.DaemonSet, error) } -func (c *daemonSetController) Get(namespace, name string, options metav1.GetOptions) (*v1.DaemonSet, error) { - result := &v1.DaemonSet{} - return result, c.client.Get(context.TODO(), namespace, name, result, options) -} +// DaemonSetHandler is function for performing any potential modifications to a DaemonSet resource. +type DaemonSetHandler func(string, *v1.DaemonSet) (*v1.DaemonSet, error) -func (c *daemonSetController) List(namespace string, opts metav1.ListOptions) (*v1.DaemonSetList, error) { - result := &v1.DaemonSetList{} - return result, c.client.List(context.TODO(), namespace, result, opts) -} +// DaemonSetIndexer computes a set of indexed values for the provided object. +type DaemonSetIndexer func(obj *v1.DaemonSet) ([]string, error) -func (c *daemonSetController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), namespace, opts) +// DaemonSetGenericController wraps wrangler/pkg/generic.Controller so that the function definitions adhere to DaemonSetController interface. +type DaemonSetGenericController struct { + generic.ControllerInterface[*v1.DaemonSet, *v1.DaemonSetList] } -func (c *daemonSetController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.DaemonSet, error) { - result := &v1.DaemonSet{} - return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *DaemonSetGenericController) OnChange(ctx context.Context, name string, sync DaemonSetHandler) { + c.ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.DaemonSet](sync)) } -type daemonSetCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *DaemonSetGenericController) OnRemove(ctx context.Context, name string, sync DaemonSetHandler) { + c.ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.DaemonSet](sync)) } -func (c *daemonSetCache) Get(namespace, name string) (*v1.DaemonSet, error) { - obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *DaemonSetGenericController) Cache() DaemonSetCache { + return &DaemonSetGenericCache{ + c.ControllerInterface.Cache(), } - return obj.(*v1.DaemonSet), nil } -func (c *daemonSetCache) List(namespace string, selector labels.Selector) (ret []*v1.DaemonSet, err error) { - - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.DaemonSet)) - }) - - return ret, err +// DaemonSetGenericCache wraps wrangler/pkg/generic.Cache so the function definitions adhere to DaemonSetCache interface. +type DaemonSetGenericCache struct { + generic.CacheInterface[*v1.DaemonSet] } -func (c *daemonSetCache) AddIndexer(indexName string, indexer DaemonSetIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.DaemonSet)) - }, - })) -} - -func (c *daemonSetCache) GetByIndex(indexName, key string) (result []*v1.DaemonSet, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.DaemonSet, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.DaemonSet)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c DaemonSetGenericCache) AddIndexer(indexName string, indexer DaemonSetIndexer) { + c.CacheInterface.AddIndexer(indexName, generic.Indexer[*v1.DaemonSet](indexer)) } type DaemonSetStatusHandler func(obj *v1.DaemonSet, status v1.DaemonSetStatus) (v1.DaemonSetStatus, error) type DaemonSetGeneratingHandler func(obj *v1.DaemonSet, status v1.DaemonSetStatus) ([]runtime.Object, v1.DaemonSetStatus, error) +func FromDaemonSetHandlerToHandler(sync DaemonSetHandler) generic.Handler { + return generic.FromObjectHandlerToHandler(generic.ObjectHandler[*v1.DaemonSet](sync)) +} + func RegisterDaemonSetStatusHandler(ctx context.Context, controller DaemonSetController, condition condition.Cond, name string, handler DaemonSetStatusHandler) { statusHandler := &daemonSetStatusHandler{ client: controller, diff --git a/pkg/generated/controllers/apps/v1/deployment.go b/pkg/generated/controllers/apps/v1/deployment.go index 2adb321e..9b654ccb 100644 --- a/pkg/generated/controllers/apps/v1/deployment.go +++ b/pkg/generated/controllers/apps/v1/deployment.go @@ -22,8 +22,6 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,237 +34,121 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type DeploymentHandler func(string, *v1.Deployment) (*v1.Deployment, error) - +// DeploymentController interface for managing Deployment resources. type DeploymentController interface { generic.ControllerMeta DeploymentClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync DeploymentHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync DeploymentHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(namespace, name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() DeploymentCache } +// DeploymentClient interface for managing Deployment resources in Kubernetes. type DeploymentClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.Deployment) (*v1.Deployment, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.Deployment) (*v1.Deployment, error) + // UpdateStatus updates the Status field of a the object and return the newly updated Object or an error. + // Will always return an error if the object does not have a status field. UpdateStatus(*v1.Deployment) (*v1.Deployment, error) + + // Delete deletes the Object in the given name. Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(namespace, name string, options metav1.GetOptions) (*v1.Deployment, error) + + // List will attempt to find multiple resources. List(namespace string, opts metav1.ListOptions) (*v1.DeploymentList, error) + + // Watch will start watching resources. Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Deployment, err error) } +// DeploymentCache interface for retrieving Deployment resources in memory. type DeploymentCache interface { + // Get returns the resources with the specified name from the cache. Get(namespace, name string) (*v1.Deployment, error) + + // List will attempt to find resources from the Cache. List(namespace string, selector labels.Selector) ([]*v1.Deployment, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer DeploymentIndexer) - GetByIndex(indexName, key string) ([]*v1.Deployment, error) -} - -type DeploymentIndexer func(obj *v1.Deployment) ([]string, error) - -type deploymentController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewDeploymentController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) DeploymentController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &deploymentController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromDeploymentHandlerToHandler(sync DeploymentHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.Deployment - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.Deployment)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *deploymentController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.Deployment)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateDeploymentDeepCopyOnChange(client DeploymentClient, obj *v1.Deployment, handler func(obj *v1.Deployment) (*v1.Deployment, error)) (*v1.Deployment, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *deploymentController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} - -func (c *deploymentController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *deploymentController) OnChange(ctx context.Context, name string, sync DeploymentHandler) { - c.AddGenericHandler(ctx, name, FromDeploymentHandlerToHandler(sync)) -} - -func (c *deploymentController) OnRemove(ctx context.Context, name string, sync DeploymentHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromDeploymentHandlerToHandler(sync))) -} - -func (c *deploymentController) Enqueue(namespace, name string) { - c.controller.Enqueue(namespace, name) -} - -func (c *deploymentController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controller.EnqueueAfter(namespace, name, duration) -} - -func (c *deploymentController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *deploymentController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *deploymentController) Cache() DeploymentCache { - return &deploymentCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *deploymentController) Create(obj *v1.Deployment) (*v1.Deployment, error) { - result := &v1.Deployment{} - return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) -} - -func (c *deploymentController) Update(obj *v1.Deployment) (*v1.Deployment, error) { - result := &v1.Deployment{} - return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} - -func (c *deploymentController) UpdateStatus(obj *v1.Deployment) (*v1.Deployment, error) { - result := &v1.Deployment{} - return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} -func (c *deploymentController) Delete(namespace, name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), namespace, name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.Deployment, error) } -func (c *deploymentController) Get(namespace, name string, options metav1.GetOptions) (*v1.Deployment, error) { - result := &v1.Deployment{} - return result, c.client.Get(context.TODO(), namespace, name, result, options) -} +// DeploymentHandler is function for performing any potential modifications to a Deployment resource. +type DeploymentHandler func(string, *v1.Deployment) (*v1.Deployment, error) -func (c *deploymentController) List(namespace string, opts metav1.ListOptions) (*v1.DeploymentList, error) { - result := &v1.DeploymentList{} - return result, c.client.List(context.TODO(), namespace, result, opts) -} +// DeploymentIndexer computes a set of indexed values for the provided object. +type DeploymentIndexer func(obj *v1.Deployment) ([]string, error) -func (c *deploymentController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), namespace, opts) +// DeploymentGenericController wraps wrangler/pkg/generic.Controller so that the function definitions adhere to DeploymentController interface. +type DeploymentGenericController struct { + generic.ControllerInterface[*v1.Deployment, *v1.DeploymentList] } -func (c *deploymentController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Deployment, error) { - result := &v1.Deployment{} - return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *DeploymentGenericController) OnChange(ctx context.Context, name string, sync DeploymentHandler) { + c.ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.Deployment](sync)) } -type deploymentCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *DeploymentGenericController) OnRemove(ctx context.Context, name string, sync DeploymentHandler) { + c.ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.Deployment](sync)) } -func (c *deploymentCache) Get(namespace, name string) (*v1.Deployment, error) { - obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *DeploymentGenericController) Cache() DeploymentCache { + return &DeploymentGenericCache{ + c.ControllerInterface.Cache(), } - return obj.(*v1.Deployment), nil } -func (c *deploymentCache) List(namespace string, selector labels.Selector) (ret []*v1.Deployment, err error) { - - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.Deployment)) - }) - - return ret, err +// DeploymentGenericCache wraps wrangler/pkg/generic.Cache so the function definitions adhere to DeploymentCache interface. +type DeploymentGenericCache struct { + generic.CacheInterface[*v1.Deployment] } -func (c *deploymentCache) AddIndexer(indexName string, indexer DeploymentIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.Deployment)) - }, - })) -} - -func (c *deploymentCache) GetByIndex(indexName, key string) (result []*v1.Deployment, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.Deployment, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.Deployment)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c DeploymentGenericCache) AddIndexer(indexName string, indexer DeploymentIndexer) { + c.CacheInterface.AddIndexer(indexName, generic.Indexer[*v1.Deployment](indexer)) } type DeploymentStatusHandler func(obj *v1.Deployment, status v1.DeploymentStatus) (v1.DeploymentStatus, error) type DeploymentGeneratingHandler func(obj *v1.Deployment, status v1.DeploymentStatus) ([]runtime.Object, v1.DeploymentStatus, error) +func FromDeploymentHandlerToHandler(sync DeploymentHandler) generic.Handler { + return generic.FromObjectHandlerToHandler(generic.ObjectHandler[*v1.Deployment](sync)) +} + func RegisterDeploymentStatusHandler(ctx context.Context, controller DeploymentController, condition condition.Cond, name string, handler DeploymentStatusHandler) { statusHandler := &deploymentStatusHandler{ client: controller, diff --git a/pkg/generated/controllers/apps/v1/interface.go b/pkg/generated/controllers/apps/v1/interface.go index c08a4c7e..f50de14e 100644 --- a/pkg/generated/controllers/apps/v1/interface.go +++ b/pkg/generated/controllers/apps/v1/interface.go @@ -20,6 +20,7 @@ package v1 import ( "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/generic" "github.com/rancher/wrangler/pkg/schemes" v1 "k8s.io/api/apps/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -45,12 +46,20 @@ type version struct { controllerFactory controller.SharedControllerFactory } -func (c *version) DaemonSet() DaemonSetController { - return NewDaemonSetController(schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "DaemonSet"}, "daemonsets", true, c.controllerFactory) +func (v *version) DaemonSet() DaemonSetController { + return &DaemonSetGenericController{ + generic.NewController[*v1.DaemonSet, *v1.DaemonSetList](schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "DaemonSet"}, "daemonsets", true, v.controllerFactory), + } } -func (c *version) Deployment() DeploymentController { - return NewDeploymentController(schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"}, "deployments", true, c.controllerFactory) + +func (v *version) Deployment() DeploymentController { + return &DeploymentGenericController{ + generic.NewController[*v1.Deployment, *v1.DeploymentList](schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "Deployment"}, "deployments", true, v.controllerFactory), + } } -func (c *version) StatefulSet() StatefulSetController { - return NewStatefulSetController(schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "StatefulSet"}, "statefulsets", true, c.controllerFactory) + +func (v *version) StatefulSet() StatefulSetController { + return &StatefulSetGenericController{ + generic.NewController[*v1.StatefulSet, *v1.StatefulSetList](schema.GroupVersionKind{Group: "apps", Version: "v1", Kind: "StatefulSet"}, "statefulsets", true, v.controllerFactory), + } } diff --git a/pkg/generated/controllers/apps/v1/statefulset.go b/pkg/generated/controllers/apps/v1/statefulset.go index a573f7c5..4a9bf5a4 100644 --- a/pkg/generated/controllers/apps/v1/statefulset.go +++ b/pkg/generated/controllers/apps/v1/statefulset.go @@ -22,8 +22,6 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,237 +34,121 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type StatefulSetHandler func(string, *v1.StatefulSet) (*v1.StatefulSet, error) - +// StatefulSetController interface for managing StatefulSet resources. type StatefulSetController interface { generic.ControllerMeta StatefulSetClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync StatefulSetHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync StatefulSetHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(namespace, name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() StatefulSetCache } +// StatefulSetClient interface for managing StatefulSet resources in Kubernetes. type StatefulSetClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.StatefulSet) (*v1.StatefulSet, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.StatefulSet) (*v1.StatefulSet, error) + // UpdateStatus updates the Status field of a the object and return the newly updated Object or an error. + // Will always return an error if the object does not have a status field. UpdateStatus(*v1.StatefulSet) (*v1.StatefulSet, error) + + // Delete deletes the Object in the given name. Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(namespace, name string, options metav1.GetOptions) (*v1.StatefulSet, error) + + // List will attempt to find multiple resources. List(namespace string, opts metav1.ListOptions) (*v1.StatefulSetList, error) + + // Watch will start watching resources. Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.StatefulSet, err error) } +// StatefulSetCache interface for retrieving StatefulSet resources in memory. type StatefulSetCache interface { + // Get returns the resources with the specified name from the cache. Get(namespace, name string) (*v1.StatefulSet, error) + + // List will attempt to find resources from the Cache. List(namespace string, selector labels.Selector) ([]*v1.StatefulSet, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer StatefulSetIndexer) - GetByIndex(indexName, key string) ([]*v1.StatefulSet, error) -} - -type StatefulSetIndexer func(obj *v1.StatefulSet) ([]string, error) - -type statefulSetController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewStatefulSetController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) StatefulSetController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &statefulSetController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromStatefulSetHandlerToHandler(sync StatefulSetHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.StatefulSet - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.StatefulSet)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *statefulSetController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.StatefulSet)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateStatefulSetDeepCopyOnChange(client StatefulSetClient, obj *v1.StatefulSet, handler func(obj *v1.StatefulSet) (*v1.StatefulSet, error)) (*v1.StatefulSet, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *statefulSetController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} - -func (c *statefulSetController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *statefulSetController) OnChange(ctx context.Context, name string, sync StatefulSetHandler) { - c.AddGenericHandler(ctx, name, FromStatefulSetHandlerToHandler(sync)) -} - -func (c *statefulSetController) OnRemove(ctx context.Context, name string, sync StatefulSetHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromStatefulSetHandlerToHandler(sync))) -} - -func (c *statefulSetController) Enqueue(namespace, name string) { - c.controller.Enqueue(namespace, name) -} - -func (c *statefulSetController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controller.EnqueueAfter(namespace, name, duration) -} - -func (c *statefulSetController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *statefulSetController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *statefulSetController) Cache() StatefulSetCache { - return &statefulSetCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *statefulSetController) Create(obj *v1.StatefulSet) (*v1.StatefulSet, error) { - result := &v1.StatefulSet{} - return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) -} - -func (c *statefulSetController) Update(obj *v1.StatefulSet) (*v1.StatefulSet, error) { - result := &v1.StatefulSet{} - return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} - -func (c *statefulSetController) UpdateStatus(obj *v1.StatefulSet) (*v1.StatefulSet, error) { - result := &v1.StatefulSet{} - return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} -func (c *statefulSetController) Delete(namespace, name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), namespace, name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.StatefulSet, error) } -func (c *statefulSetController) Get(namespace, name string, options metav1.GetOptions) (*v1.StatefulSet, error) { - result := &v1.StatefulSet{} - return result, c.client.Get(context.TODO(), namespace, name, result, options) -} +// StatefulSetHandler is function for performing any potential modifications to a StatefulSet resource. +type StatefulSetHandler func(string, *v1.StatefulSet) (*v1.StatefulSet, error) -func (c *statefulSetController) List(namespace string, opts metav1.ListOptions) (*v1.StatefulSetList, error) { - result := &v1.StatefulSetList{} - return result, c.client.List(context.TODO(), namespace, result, opts) -} +// StatefulSetIndexer computes a set of indexed values for the provided object. +type StatefulSetIndexer func(obj *v1.StatefulSet) ([]string, error) -func (c *statefulSetController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), namespace, opts) +// StatefulSetGenericController wraps wrangler/pkg/generic.Controller so that the function definitions adhere to StatefulSetController interface. +type StatefulSetGenericController struct { + generic.ControllerInterface[*v1.StatefulSet, *v1.StatefulSetList] } -func (c *statefulSetController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.StatefulSet, error) { - result := &v1.StatefulSet{} - return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *StatefulSetGenericController) OnChange(ctx context.Context, name string, sync StatefulSetHandler) { + c.ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.StatefulSet](sync)) } -type statefulSetCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *StatefulSetGenericController) OnRemove(ctx context.Context, name string, sync StatefulSetHandler) { + c.ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.StatefulSet](sync)) } -func (c *statefulSetCache) Get(namespace, name string) (*v1.StatefulSet, error) { - obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *StatefulSetGenericController) Cache() StatefulSetCache { + return &StatefulSetGenericCache{ + c.ControllerInterface.Cache(), } - return obj.(*v1.StatefulSet), nil } -func (c *statefulSetCache) List(namespace string, selector labels.Selector) (ret []*v1.StatefulSet, err error) { - - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.StatefulSet)) - }) - - return ret, err +// StatefulSetGenericCache wraps wrangler/pkg/generic.Cache so the function definitions adhere to StatefulSetCache interface. +type StatefulSetGenericCache struct { + generic.CacheInterface[*v1.StatefulSet] } -func (c *statefulSetCache) AddIndexer(indexName string, indexer StatefulSetIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.StatefulSet)) - }, - })) -} - -func (c *statefulSetCache) GetByIndex(indexName, key string) (result []*v1.StatefulSet, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.StatefulSet, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.StatefulSet)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c StatefulSetGenericCache) AddIndexer(indexName string, indexer StatefulSetIndexer) { + c.CacheInterface.AddIndexer(indexName, generic.Indexer[*v1.StatefulSet](indexer)) } type StatefulSetStatusHandler func(obj *v1.StatefulSet, status v1.StatefulSetStatus) (v1.StatefulSetStatus, error) type StatefulSetGeneratingHandler func(obj *v1.StatefulSet, status v1.StatefulSetStatus) ([]runtime.Object, v1.StatefulSetStatus, error) +func FromStatefulSetHandlerToHandler(sync StatefulSetHandler) generic.Handler { + return generic.FromObjectHandlerToHandler(generic.ObjectHandler[*v1.StatefulSet](sync)) +} + func RegisterStatefulSetStatusHandler(ctx context.Context, controller StatefulSetController, condition condition.Cond, name string, handler StatefulSetStatusHandler) { statusHandler := &statefulSetStatusHandler{ client: controller, diff --git a/pkg/generated/controllers/batch/v1/interface.go b/pkg/generated/controllers/batch/v1/interface.go index abaf5ad5..68b38507 100644 --- a/pkg/generated/controllers/batch/v1/interface.go +++ b/pkg/generated/controllers/batch/v1/interface.go @@ -20,6 +20,7 @@ package v1 import ( "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/generic" "github.com/rancher/wrangler/pkg/schemes" v1 "k8s.io/api/batch/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -43,6 +44,8 @@ type version struct { controllerFactory controller.SharedControllerFactory } -func (c *version) Job() JobController { - return NewJobController(schema.GroupVersionKind{Group: "batch", Version: "v1", Kind: "Job"}, "jobs", true, c.controllerFactory) +func (v *version) Job() JobController { + return &JobGenericController{ + generic.NewController[*v1.Job, *v1.JobList](schema.GroupVersionKind{Group: "batch", Version: "v1", Kind: "Job"}, "jobs", true, v.controllerFactory), + } } diff --git a/pkg/generated/controllers/batch/v1/job.go b/pkg/generated/controllers/batch/v1/job.go index ca5b9355..72e00792 100644 --- a/pkg/generated/controllers/batch/v1/job.go +++ b/pkg/generated/controllers/batch/v1/job.go @@ -22,8 +22,6 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,237 +34,121 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type JobHandler func(string, *v1.Job) (*v1.Job, error) - +// JobController interface for managing Job resources. type JobController interface { generic.ControllerMeta JobClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync JobHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync JobHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(namespace, name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() JobCache } +// JobClient interface for managing Job resources in Kubernetes. type JobClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.Job) (*v1.Job, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.Job) (*v1.Job, error) + // UpdateStatus updates the Status field of a the object and return the newly updated Object or an error. + // Will always return an error if the object does not have a status field. UpdateStatus(*v1.Job) (*v1.Job, error) + + // Delete deletes the Object in the given name. Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(namespace, name string, options metav1.GetOptions) (*v1.Job, error) + + // List will attempt to find multiple resources. List(namespace string, opts metav1.ListOptions) (*v1.JobList, error) + + // Watch will start watching resources. Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Job, err error) } +// JobCache interface for retrieving Job resources in memory. type JobCache interface { + // Get returns the resources with the specified name from the cache. Get(namespace, name string) (*v1.Job, error) + + // List will attempt to find resources from the Cache. List(namespace string, selector labels.Selector) ([]*v1.Job, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer JobIndexer) - GetByIndex(indexName, key string) ([]*v1.Job, error) -} - -type JobIndexer func(obj *v1.Job) ([]string, error) - -type jobController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewJobController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) JobController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &jobController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromJobHandlerToHandler(sync JobHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.Job - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.Job)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *jobController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.Job)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateJobDeepCopyOnChange(client JobClient, obj *v1.Job, handler func(obj *v1.Job) (*v1.Job, error)) (*v1.Job, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *jobController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} - -func (c *jobController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *jobController) OnChange(ctx context.Context, name string, sync JobHandler) { - c.AddGenericHandler(ctx, name, FromJobHandlerToHandler(sync)) -} - -func (c *jobController) OnRemove(ctx context.Context, name string, sync JobHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromJobHandlerToHandler(sync))) -} - -func (c *jobController) Enqueue(namespace, name string) { - c.controller.Enqueue(namespace, name) -} - -func (c *jobController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controller.EnqueueAfter(namespace, name, duration) -} - -func (c *jobController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *jobController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *jobController) Cache() JobCache { - return &jobCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *jobController) Create(obj *v1.Job) (*v1.Job, error) { - result := &v1.Job{} - return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) -} - -func (c *jobController) Update(obj *v1.Job) (*v1.Job, error) { - result := &v1.Job{} - return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} - -func (c *jobController) UpdateStatus(obj *v1.Job) (*v1.Job, error) { - result := &v1.Job{} - return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} -func (c *jobController) Delete(namespace, name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), namespace, name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.Job, error) } -func (c *jobController) Get(namespace, name string, options metav1.GetOptions) (*v1.Job, error) { - result := &v1.Job{} - return result, c.client.Get(context.TODO(), namespace, name, result, options) -} +// JobHandler is function for performing any potential modifications to a Job resource. +type JobHandler func(string, *v1.Job) (*v1.Job, error) -func (c *jobController) List(namespace string, opts metav1.ListOptions) (*v1.JobList, error) { - result := &v1.JobList{} - return result, c.client.List(context.TODO(), namespace, result, opts) -} +// JobIndexer computes a set of indexed values for the provided object. +type JobIndexer func(obj *v1.Job) ([]string, error) -func (c *jobController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), namespace, opts) +// JobGenericController wraps wrangler/pkg/generic.Controller so that the function definitions adhere to JobController interface. +type JobGenericController struct { + generic.ControllerInterface[*v1.Job, *v1.JobList] } -func (c *jobController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Job, error) { - result := &v1.Job{} - return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *JobGenericController) OnChange(ctx context.Context, name string, sync JobHandler) { + c.ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.Job](sync)) } -type jobCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *JobGenericController) OnRemove(ctx context.Context, name string, sync JobHandler) { + c.ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.Job](sync)) } -func (c *jobCache) Get(namespace, name string) (*v1.Job, error) { - obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *JobGenericController) Cache() JobCache { + return &JobGenericCache{ + c.ControllerInterface.Cache(), } - return obj.(*v1.Job), nil } -func (c *jobCache) List(namespace string, selector labels.Selector) (ret []*v1.Job, err error) { - - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.Job)) - }) - - return ret, err +// JobGenericCache wraps wrangler/pkg/generic.Cache so the function definitions adhere to JobCache interface. +type JobGenericCache struct { + generic.CacheInterface[*v1.Job] } -func (c *jobCache) AddIndexer(indexName string, indexer JobIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.Job)) - }, - })) -} - -func (c *jobCache) GetByIndex(indexName, key string) (result []*v1.Job, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.Job, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.Job)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c JobGenericCache) AddIndexer(indexName string, indexer JobIndexer) { + c.CacheInterface.AddIndexer(indexName, generic.Indexer[*v1.Job](indexer)) } type JobStatusHandler func(obj *v1.Job, status v1.JobStatus) (v1.JobStatus, error) type JobGeneratingHandler func(obj *v1.Job, status v1.JobStatus) ([]runtime.Object, v1.JobStatus, error) +func FromJobHandlerToHandler(sync JobHandler) generic.Handler { + return generic.FromObjectHandlerToHandler(generic.ObjectHandler[*v1.Job](sync)) +} + func RegisterJobStatusHandler(ctx context.Context, controller JobController, condition condition.Cond, name string, handler JobStatusHandler) { statusHandler := &jobStatusHandler{ client: controller, diff --git a/pkg/generated/controllers/coordination.k8s.io/v1/interface.go b/pkg/generated/controllers/coordination.k8s.io/v1/interface.go index 7f4242cd..aaf4d3c8 100644 --- a/pkg/generated/controllers/coordination.k8s.io/v1/interface.go +++ b/pkg/generated/controllers/coordination.k8s.io/v1/interface.go @@ -20,6 +20,7 @@ package v1 import ( "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/generic" "github.com/rancher/wrangler/pkg/schemes" v1 "k8s.io/api/coordination/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -43,6 +44,8 @@ type version struct { controllerFactory controller.SharedControllerFactory } -func (c *version) Lease() LeaseController { - return NewLeaseController(schema.GroupVersionKind{Group: "coordination.k8s.io", Version: "v1", Kind: "Lease"}, "leases", true, c.controllerFactory) +func (v *version) Lease() LeaseController { + return &LeaseGenericController{ + generic.NewController[*v1.Lease, *v1.LeaseList](schema.GroupVersionKind{Group: "coordination.k8s.io", Version: "v1", Kind: "Lease"}, "leases", true, v.controllerFactory), + } } diff --git a/pkg/generated/controllers/coordination.k8s.io/v1/lease.go b/pkg/generated/controllers/coordination.k8s.io/v1/lease.go index b968da48..225f4e96 100644 --- a/pkg/generated/controllers/coordination.k8s.io/v1/lease.go +++ b/pkg/generated/controllers/coordination.k8s.io/v1/lease.go @@ -22,235 +22,111 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/coordination/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type LeaseHandler func(string, *v1.Lease) (*v1.Lease, error) - +// LeaseController interface for managing Lease resources. type LeaseController interface { generic.ControllerMeta LeaseClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync LeaseHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync LeaseHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(namespace, name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() LeaseCache } +// LeaseClient interface for managing Lease resources in Kubernetes. type LeaseClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.Lease) (*v1.Lease, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.Lease) (*v1.Lease, error) + // Delete deletes the Object in the given name. Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(namespace, name string, options metav1.GetOptions) (*v1.Lease, error) + + // List will attempt to find multiple resources. List(namespace string, opts metav1.ListOptions) (*v1.LeaseList, error) + + // Watch will start watching resources. Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Lease, err error) } +// LeaseCache interface for retrieving Lease resources in memory. type LeaseCache interface { + // Get returns the resources with the specified name from the cache. Get(namespace, name string) (*v1.Lease, error) + + // List will attempt to find resources from the Cache. List(namespace string, selector labels.Selector) ([]*v1.Lease, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer LeaseIndexer) - GetByIndex(indexName, key string) ([]*v1.Lease, error) -} - -type LeaseIndexer func(obj *v1.Lease) ([]string, error) - -type leaseController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewLeaseController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) LeaseController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &leaseController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromLeaseHandlerToHandler(sync LeaseHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.Lease - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.Lease)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *leaseController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.Lease)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateLeaseDeepCopyOnChange(client LeaseClient, obj *v1.Lease, handler func(obj *v1.Lease) (*v1.Lease, error)) (*v1.Lease, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *leaseController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} -func (c *leaseController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *leaseController) OnChange(ctx context.Context, name string, sync LeaseHandler) { - c.AddGenericHandler(ctx, name, FromLeaseHandlerToHandler(sync)) -} - -func (c *leaseController) OnRemove(ctx context.Context, name string, sync LeaseHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromLeaseHandlerToHandler(sync))) -} - -func (c *leaseController) Enqueue(namespace, name string) { - c.controller.Enqueue(namespace, name) -} - -func (c *leaseController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controller.EnqueueAfter(namespace, name, duration) -} - -func (c *leaseController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *leaseController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *leaseController) Cache() LeaseCache { - return &leaseCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *leaseController) Create(obj *v1.Lease) (*v1.Lease, error) { - result := &v1.Lease{} - return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) -} - -func (c *leaseController) Update(obj *v1.Lease) (*v1.Lease, error) { - result := &v1.Lease{} - return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} - -func (c *leaseController) Delete(namespace, name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), namespace, name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.Lease, error) } -func (c *leaseController) Get(namespace, name string, options metav1.GetOptions) (*v1.Lease, error) { - result := &v1.Lease{} - return result, c.client.Get(context.TODO(), namespace, name, result, options) -} +// LeaseHandler is function for performing any potential modifications to a Lease resource. +type LeaseHandler func(string, *v1.Lease) (*v1.Lease, error) -func (c *leaseController) List(namespace string, opts metav1.ListOptions) (*v1.LeaseList, error) { - result := &v1.LeaseList{} - return result, c.client.List(context.TODO(), namespace, result, opts) -} +// LeaseIndexer computes a set of indexed values for the provided object. +type LeaseIndexer func(obj *v1.Lease) ([]string, error) -func (c *leaseController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), namespace, opts) +// LeaseGenericController wraps wrangler/pkg/generic.Controller so that the function definitions adhere to LeaseController interface. +type LeaseGenericController struct { + generic.ControllerInterface[*v1.Lease, *v1.LeaseList] } -func (c *leaseController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Lease, error) { - result := &v1.Lease{} - return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *LeaseGenericController) OnChange(ctx context.Context, name string, sync LeaseHandler) { + c.ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.Lease](sync)) } -type leaseCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *LeaseGenericController) OnRemove(ctx context.Context, name string, sync LeaseHandler) { + c.ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.Lease](sync)) } -func (c *leaseCache) Get(namespace, name string) (*v1.Lease, error) { - obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *LeaseGenericController) Cache() LeaseCache { + return &LeaseGenericCache{ + c.ControllerInterface.Cache(), } - return obj.(*v1.Lease), nil -} - -func (c *leaseCache) List(namespace string, selector labels.Selector) (ret []*v1.Lease, err error) { - - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.Lease)) - }) - - return ret, err } -func (c *leaseCache) AddIndexer(indexName string, indexer LeaseIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.Lease)) - }, - })) +// LeaseGenericCache wraps wrangler/pkg/generic.Cache so the function definitions adhere to LeaseCache interface. +type LeaseGenericCache struct { + generic.CacheInterface[*v1.Lease] } -func (c *leaseCache) GetByIndex(indexName, key string) (result []*v1.Lease, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.Lease, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.Lease)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c LeaseGenericCache) AddIndexer(indexName string, indexer LeaseIndexer) { + c.CacheInterface.AddIndexer(indexName, generic.Indexer[*v1.Lease](indexer)) } diff --git a/pkg/generated/controllers/core/v1/configmap.go b/pkg/generated/controllers/core/v1/configmap.go index d56e1d87..62eb94c1 100644 --- a/pkg/generated/controllers/core/v1/configmap.go +++ b/pkg/generated/controllers/core/v1/configmap.go @@ -22,235 +22,111 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type ConfigMapHandler func(string, *v1.ConfigMap) (*v1.ConfigMap, error) - +// ConfigMapController interface for managing ConfigMap resources. type ConfigMapController interface { generic.ControllerMeta ConfigMapClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync ConfigMapHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync ConfigMapHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(namespace, name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() ConfigMapCache } +// ConfigMapClient interface for managing ConfigMap resources in Kubernetes. type ConfigMapClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.ConfigMap) (*v1.ConfigMap, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.ConfigMap) (*v1.ConfigMap, error) + // Delete deletes the Object in the given name. Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(namespace, name string, options metav1.GetOptions) (*v1.ConfigMap, error) + + // List will attempt to find multiple resources. List(namespace string, opts metav1.ListOptions) (*v1.ConfigMapList, error) + + // Watch will start watching resources. Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.ConfigMap, err error) } +// ConfigMapCache interface for retrieving ConfigMap resources in memory. type ConfigMapCache interface { + // Get returns the resources with the specified name from the cache. Get(namespace, name string) (*v1.ConfigMap, error) + + // List will attempt to find resources from the Cache. List(namespace string, selector labels.Selector) ([]*v1.ConfigMap, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer ConfigMapIndexer) - GetByIndex(indexName, key string) ([]*v1.ConfigMap, error) -} - -type ConfigMapIndexer func(obj *v1.ConfigMap) ([]string, error) - -type configMapController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewConfigMapController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) ConfigMapController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &configMapController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromConfigMapHandlerToHandler(sync ConfigMapHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.ConfigMap - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.ConfigMap)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *configMapController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.ConfigMap)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateConfigMapDeepCopyOnChange(client ConfigMapClient, obj *v1.ConfigMap, handler func(obj *v1.ConfigMap) (*v1.ConfigMap, error)) (*v1.ConfigMap, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *configMapController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} -func (c *configMapController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *configMapController) OnChange(ctx context.Context, name string, sync ConfigMapHandler) { - c.AddGenericHandler(ctx, name, FromConfigMapHandlerToHandler(sync)) -} - -func (c *configMapController) OnRemove(ctx context.Context, name string, sync ConfigMapHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromConfigMapHandlerToHandler(sync))) -} - -func (c *configMapController) Enqueue(namespace, name string) { - c.controller.Enqueue(namespace, name) -} - -func (c *configMapController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controller.EnqueueAfter(namespace, name, duration) -} - -func (c *configMapController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *configMapController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *configMapController) Cache() ConfigMapCache { - return &configMapCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *configMapController) Create(obj *v1.ConfigMap) (*v1.ConfigMap, error) { - result := &v1.ConfigMap{} - return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) -} - -func (c *configMapController) Update(obj *v1.ConfigMap) (*v1.ConfigMap, error) { - result := &v1.ConfigMap{} - return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} - -func (c *configMapController) Delete(namespace, name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), namespace, name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.ConfigMap, error) } -func (c *configMapController) Get(namespace, name string, options metav1.GetOptions) (*v1.ConfigMap, error) { - result := &v1.ConfigMap{} - return result, c.client.Get(context.TODO(), namespace, name, result, options) -} +// ConfigMapHandler is function for performing any potential modifications to a ConfigMap resource. +type ConfigMapHandler func(string, *v1.ConfigMap) (*v1.ConfigMap, error) -func (c *configMapController) List(namespace string, opts metav1.ListOptions) (*v1.ConfigMapList, error) { - result := &v1.ConfigMapList{} - return result, c.client.List(context.TODO(), namespace, result, opts) -} +// ConfigMapIndexer computes a set of indexed values for the provided object. +type ConfigMapIndexer func(obj *v1.ConfigMap) ([]string, error) -func (c *configMapController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), namespace, opts) +// ConfigMapGenericController wraps wrangler/pkg/generic.Controller so that the function definitions adhere to ConfigMapController interface. +type ConfigMapGenericController struct { + generic.ControllerInterface[*v1.ConfigMap, *v1.ConfigMapList] } -func (c *configMapController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.ConfigMap, error) { - result := &v1.ConfigMap{} - return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *ConfigMapGenericController) OnChange(ctx context.Context, name string, sync ConfigMapHandler) { + c.ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.ConfigMap](sync)) } -type configMapCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *ConfigMapGenericController) OnRemove(ctx context.Context, name string, sync ConfigMapHandler) { + c.ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.ConfigMap](sync)) } -func (c *configMapCache) Get(namespace, name string) (*v1.ConfigMap, error) { - obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *ConfigMapGenericController) Cache() ConfigMapCache { + return &ConfigMapGenericCache{ + c.ControllerInterface.Cache(), } - return obj.(*v1.ConfigMap), nil -} - -func (c *configMapCache) List(namespace string, selector labels.Selector) (ret []*v1.ConfigMap, err error) { - - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.ConfigMap)) - }) - - return ret, err } -func (c *configMapCache) AddIndexer(indexName string, indexer ConfigMapIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.ConfigMap)) - }, - })) +// ConfigMapGenericCache wraps wrangler/pkg/generic.Cache so the function definitions adhere to ConfigMapCache interface. +type ConfigMapGenericCache struct { + generic.CacheInterface[*v1.ConfigMap] } -func (c *configMapCache) GetByIndex(indexName, key string) (result []*v1.ConfigMap, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.ConfigMap, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.ConfigMap)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c ConfigMapGenericCache) AddIndexer(indexName string, indexer ConfigMapIndexer) { + c.CacheInterface.AddIndexer(indexName, generic.Indexer[*v1.ConfigMap](indexer)) } diff --git a/pkg/generated/controllers/core/v1/endpoints.go b/pkg/generated/controllers/core/v1/endpoints.go index 742c38be..bf3133cc 100644 --- a/pkg/generated/controllers/core/v1/endpoints.go +++ b/pkg/generated/controllers/core/v1/endpoints.go @@ -22,235 +22,111 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type EndpointsHandler func(string, *v1.Endpoints) (*v1.Endpoints, error) - +// EndpointsController interface for managing Endpoints resources. type EndpointsController interface { generic.ControllerMeta EndpointsClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync EndpointsHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync EndpointsHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(namespace, name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() EndpointsCache } +// EndpointsClient interface for managing Endpoints resources in Kubernetes. type EndpointsClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.Endpoints) (*v1.Endpoints, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.Endpoints) (*v1.Endpoints, error) + // Delete deletes the Object in the given name. Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(namespace, name string, options metav1.GetOptions) (*v1.Endpoints, error) + + // List will attempt to find multiple resources. List(namespace string, opts metav1.ListOptions) (*v1.EndpointsList, error) + + // Watch will start watching resources. Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Endpoints, err error) } +// EndpointsCache interface for retrieving Endpoints resources in memory. type EndpointsCache interface { + // Get returns the resources with the specified name from the cache. Get(namespace, name string) (*v1.Endpoints, error) + + // List will attempt to find resources from the Cache. List(namespace string, selector labels.Selector) ([]*v1.Endpoints, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer EndpointsIndexer) - GetByIndex(indexName, key string) ([]*v1.Endpoints, error) -} - -type EndpointsIndexer func(obj *v1.Endpoints) ([]string, error) - -type endpointsController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewEndpointsController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) EndpointsController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &endpointsController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromEndpointsHandlerToHandler(sync EndpointsHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.Endpoints - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.Endpoints)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *endpointsController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.Endpoints)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateEndpointsDeepCopyOnChange(client EndpointsClient, obj *v1.Endpoints, handler func(obj *v1.Endpoints) (*v1.Endpoints, error)) (*v1.Endpoints, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *endpointsController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} -func (c *endpointsController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *endpointsController) OnChange(ctx context.Context, name string, sync EndpointsHandler) { - c.AddGenericHandler(ctx, name, FromEndpointsHandlerToHandler(sync)) -} - -func (c *endpointsController) OnRemove(ctx context.Context, name string, sync EndpointsHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromEndpointsHandlerToHandler(sync))) -} - -func (c *endpointsController) Enqueue(namespace, name string) { - c.controller.Enqueue(namespace, name) -} - -func (c *endpointsController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controller.EnqueueAfter(namespace, name, duration) -} - -func (c *endpointsController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *endpointsController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *endpointsController) Cache() EndpointsCache { - return &endpointsCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *endpointsController) Create(obj *v1.Endpoints) (*v1.Endpoints, error) { - result := &v1.Endpoints{} - return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) -} - -func (c *endpointsController) Update(obj *v1.Endpoints) (*v1.Endpoints, error) { - result := &v1.Endpoints{} - return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} - -func (c *endpointsController) Delete(namespace, name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), namespace, name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.Endpoints, error) } -func (c *endpointsController) Get(namespace, name string, options metav1.GetOptions) (*v1.Endpoints, error) { - result := &v1.Endpoints{} - return result, c.client.Get(context.TODO(), namespace, name, result, options) -} +// EndpointsHandler is function for performing any potential modifications to a Endpoints resource. +type EndpointsHandler func(string, *v1.Endpoints) (*v1.Endpoints, error) -func (c *endpointsController) List(namespace string, opts metav1.ListOptions) (*v1.EndpointsList, error) { - result := &v1.EndpointsList{} - return result, c.client.List(context.TODO(), namespace, result, opts) -} +// EndpointsIndexer computes a set of indexed values for the provided object. +type EndpointsIndexer func(obj *v1.Endpoints) ([]string, error) -func (c *endpointsController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), namespace, opts) +// EndpointsGenericController wraps wrangler/pkg/generic.Controller so that the function definitions adhere to EndpointsController interface. +type EndpointsGenericController struct { + generic.ControllerInterface[*v1.Endpoints, *v1.EndpointsList] } -func (c *endpointsController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Endpoints, error) { - result := &v1.Endpoints{} - return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *EndpointsGenericController) OnChange(ctx context.Context, name string, sync EndpointsHandler) { + c.ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.Endpoints](sync)) } -type endpointsCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *EndpointsGenericController) OnRemove(ctx context.Context, name string, sync EndpointsHandler) { + c.ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.Endpoints](sync)) } -func (c *endpointsCache) Get(namespace, name string) (*v1.Endpoints, error) { - obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *EndpointsGenericController) Cache() EndpointsCache { + return &EndpointsGenericCache{ + c.ControllerInterface.Cache(), } - return obj.(*v1.Endpoints), nil -} - -func (c *endpointsCache) List(namespace string, selector labels.Selector) (ret []*v1.Endpoints, err error) { - - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.Endpoints)) - }) - - return ret, err } -func (c *endpointsCache) AddIndexer(indexName string, indexer EndpointsIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.Endpoints)) - }, - })) +// EndpointsGenericCache wraps wrangler/pkg/generic.Cache so the function definitions adhere to EndpointsCache interface. +type EndpointsGenericCache struct { + generic.CacheInterface[*v1.Endpoints] } -func (c *endpointsCache) GetByIndex(indexName, key string) (result []*v1.Endpoints, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.Endpoints, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.Endpoints)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c EndpointsGenericCache) AddIndexer(indexName string, indexer EndpointsIndexer) { + c.CacheInterface.AddIndexer(indexName, generic.Indexer[*v1.Endpoints](indexer)) } diff --git a/pkg/generated/controllers/core/v1/event.go b/pkg/generated/controllers/core/v1/event.go index b052ef91..ea61ed2f 100644 --- a/pkg/generated/controllers/core/v1/event.go +++ b/pkg/generated/controllers/core/v1/event.go @@ -22,235 +22,111 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type EventHandler func(string, *v1.Event) (*v1.Event, error) - +// EventController interface for managing Event resources. type EventController interface { generic.ControllerMeta EventClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync EventHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync EventHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(namespace, name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() EventCache } +// EventClient interface for managing Event resources in Kubernetes. type EventClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.Event) (*v1.Event, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.Event) (*v1.Event, error) + // Delete deletes the Object in the given name. Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(namespace, name string, options metav1.GetOptions) (*v1.Event, error) + + // List will attempt to find multiple resources. List(namespace string, opts metav1.ListOptions) (*v1.EventList, error) + + // Watch will start watching resources. Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Event, err error) } +// EventCache interface for retrieving Event resources in memory. type EventCache interface { + // Get returns the resources with the specified name from the cache. Get(namespace, name string) (*v1.Event, error) + + // List will attempt to find resources from the Cache. List(namespace string, selector labels.Selector) ([]*v1.Event, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer EventIndexer) - GetByIndex(indexName, key string) ([]*v1.Event, error) -} - -type EventIndexer func(obj *v1.Event) ([]string, error) - -type eventController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewEventController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) EventController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &eventController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromEventHandlerToHandler(sync EventHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.Event - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.Event)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *eventController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.Event)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateEventDeepCopyOnChange(client EventClient, obj *v1.Event, handler func(obj *v1.Event) (*v1.Event, error)) (*v1.Event, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *eventController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} -func (c *eventController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *eventController) OnChange(ctx context.Context, name string, sync EventHandler) { - c.AddGenericHandler(ctx, name, FromEventHandlerToHandler(sync)) -} - -func (c *eventController) OnRemove(ctx context.Context, name string, sync EventHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromEventHandlerToHandler(sync))) -} - -func (c *eventController) Enqueue(namespace, name string) { - c.controller.Enqueue(namespace, name) -} - -func (c *eventController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controller.EnqueueAfter(namespace, name, duration) -} - -func (c *eventController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *eventController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *eventController) Cache() EventCache { - return &eventCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *eventController) Create(obj *v1.Event) (*v1.Event, error) { - result := &v1.Event{} - return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) -} - -func (c *eventController) Update(obj *v1.Event) (*v1.Event, error) { - result := &v1.Event{} - return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} - -func (c *eventController) Delete(namespace, name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), namespace, name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.Event, error) } -func (c *eventController) Get(namespace, name string, options metav1.GetOptions) (*v1.Event, error) { - result := &v1.Event{} - return result, c.client.Get(context.TODO(), namespace, name, result, options) -} +// EventHandler is function for performing any potential modifications to a Event resource. +type EventHandler func(string, *v1.Event) (*v1.Event, error) -func (c *eventController) List(namespace string, opts metav1.ListOptions) (*v1.EventList, error) { - result := &v1.EventList{} - return result, c.client.List(context.TODO(), namespace, result, opts) -} +// EventIndexer computes a set of indexed values for the provided object. +type EventIndexer func(obj *v1.Event) ([]string, error) -func (c *eventController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), namespace, opts) +// EventGenericController wraps wrangler/pkg/generic.Controller so that the function definitions adhere to EventController interface. +type EventGenericController struct { + generic.ControllerInterface[*v1.Event, *v1.EventList] } -func (c *eventController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Event, error) { - result := &v1.Event{} - return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *EventGenericController) OnChange(ctx context.Context, name string, sync EventHandler) { + c.ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.Event](sync)) } -type eventCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *EventGenericController) OnRemove(ctx context.Context, name string, sync EventHandler) { + c.ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.Event](sync)) } -func (c *eventCache) Get(namespace, name string) (*v1.Event, error) { - obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *EventGenericController) Cache() EventCache { + return &EventGenericCache{ + c.ControllerInterface.Cache(), } - return obj.(*v1.Event), nil -} - -func (c *eventCache) List(namespace string, selector labels.Selector) (ret []*v1.Event, err error) { - - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.Event)) - }) - - return ret, err } -func (c *eventCache) AddIndexer(indexName string, indexer EventIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.Event)) - }, - })) +// EventGenericCache wraps wrangler/pkg/generic.Cache so the function definitions adhere to EventCache interface. +type EventGenericCache struct { + generic.CacheInterface[*v1.Event] } -func (c *eventCache) GetByIndex(indexName, key string) (result []*v1.Event, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.Event, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.Event)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c EventGenericCache) AddIndexer(indexName string, indexer EventIndexer) { + c.CacheInterface.AddIndexer(indexName, generic.Indexer[*v1.Event](indexer)) } diff --git a/pkg/generated/controllers/core/v1/interface.go b/pkg/generated/controllers/core/v1/interface.go index a53c56bd..150ea2c7 100644 --- a/pkg/generated/controllers/core/v1/interface.go +++ b/pkg/generated/controllers/core/v1/interface.go @@ -20,6 +20,7 @@ package v1 import ( "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/generic" "github.com/rancher/wrangler/pkg/schemes" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -53,36 +54,68 @@ type version struct { controllerFactory controller.SharedControllerFactory } -func (c *version) ConfigMap() ConfigMapController { - return NewConfigMapController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "ConfigMap"}, "configmaps", true, c.controllerFactory) +func (v *version) ConfigMap() ConfigMapController { + return &ConfigMapGenericController{ + generic.NewController[*v1.ConfigMap, *v1.ConfigMapList](schema.GroupVersionKind{Group: "", Version: "v1", Kind: "ConfigMap"}, "configmaps", true, v.controllerFactory), + } } -func (c *version) Endpoints() EndpointsController { - return NewEndpointsController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Endpoints"}, "endpoints", true, c.controllerFactory) + +func (v *version) Endpoints() EndpointsController { + return &EndpointsGenericController{ + generic.NewController[*v1.Endpoints, *v1.EndpointsList](schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Endpoints"}, "endpoints", true, v.controllerFactory), + } } -func (c *version) Event() EventController { - return NewEventController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Event"}, "events", true, c.controllerFactory) + +func (v *version) Event() EventController { + return &EventGenericController{ + generic.NewController[*v1.Event, *v1.EventList](schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Event"}, "events", true, v.controllerFactory), + } } -func (c *version) Namespace() NamespaceController { - return NewNamespaceController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Namespace"}, "namespaces", false, c.controllerFactory) + +func (v *version) Namespace() NamespaceController { + return &NamespaceGenericController{ + generic.NewNonNamespacedController[*v1.Namespace, *v1.NamespaceList](schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Namespace"}, "namespaces", v.controllerFactory), + } } -func (c *version) Node() NodeController { - return NewNodeController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Node"}, "nodes", false, c.controllerFactory) + +func (v *version) Node() NodeController { + return &NodeGenericController{ + generic.NewNonNamespacedController[*v1.Node, *v1.NodeList](schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Node"}, "nodes", v.controllerFactory), + } } -func (c *version) PersistentVolume() PersistentVolumeController { - return NewPersistentVolumeController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "PersistentVolume"}, "persistentvolumes", false, c.controllerFactory) + +func (v *version) PersistentVolume() PersistentVolumeController { + return &PersistentVolumeGenericController{ + generic.NewNonNamespacedController[*v1.PersistentVolume, *v1.PersistentVolumeList](schema.GroupVersionKind{Group: "", Version: "v1", Kind: "PersistentVolume"}, "persistentvolumes", v.controllerFactory), + } } -func (c *version) PersistentVolumeClaim() PersistentVolumeClaimController { - return NewPersistentVolumeClaimController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "PersistentVolumeClaim"}, "persistentvolumeclaims", true, c.controllerFactory) + +func (v *version) PersistentVolumeClaim() PersistentVolumeClaimController { + return &PersistentVolumeClaimGenericController{ + generic.NewController[*v1.PersistentVolumeClaim, *v1.PersistentVolumeClaimList](schema.GroupVersionKind{Group: "", Version: "v1", Kind: "PersistentVolumeClaim"}, "persistentvolumeclaims", true, v.controllerFactory), + } } -func (c *version) Pod() PodController { - return NewPodController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Pod"}, "pods", true, c.controllerFactory) + +func (v *version) Pod() PodController { + return &PodGenericController{ + generic.NewController[*v1.Pod, *v1.PodList](schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Pod"}, "pods", true, v.controllerFactory), + } } -func (c *version) Secret() SecretController { - return NewSecretController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Secret"}, "secrets", true, c.controllerFactory) + +func (v *version) Secret() SecretController { + return &SecretGenericController{ + generic.NewController[*v1.Secret, *v1.SecretList](schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Secret"}, "secrets", true, v.controllerFactory), + } } -func (c *version) Service() ServiceController { - return NewServiceController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Service"}, "services", true, c.controllerFactory) + +func (v *version) Service() ServiceController { + return &ServiceGenericController{ + generic.NewController[*v1.Service, *v1.ServiceList](schema.GroupVersionKind{Group: "", Version: "v1", Kind: "Service"}, "services", true, v.controllerFactory), + } } -func (c *version) ServiceAccount() ServiceAccountController { - return NewServiceAccountController(schema.GroupVersionKind{Group: "", Version: "v1", Kind: "ServiceAccount"}, "serviceaccounts", true, c.controllerFactory) + +func (v *version) ServiceAccount() ServiceAccountController { + return &ServiceAccountGenericController{ + generic.NewController[*v1.ServiceAccount, *v1.ServiceAccountList](schema.GroupVersionKind{Group: "", Version: "v1", Kind: "ServiceAccount"}, "serviceaccounts", true, v.controllerFactory), + } } diff --git a/pkg/generated/controllers/core/v1/namespace.go b/pkg/generated/controllers/core/v1/namespace.go index 83d04ac6..77034719 100644 --- a/pkg/generated/controllers/core/v1/namespace.go +++ b/pkg/generated/controllers/core/v1/namespace.go @@ -22,8 +22,6 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,237 +34,121 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type NamespaceHandler func(string, *v1.Namespace) (*v1.Namespace, error) - +// NamespaceController interface for managing Namespace resources. type NamespaceController interface { generic.ControllerMeta NamespaceClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync NamespaceHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync NamespaceHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() NamespaceCache } +// NamespaceClient interface for managing Namespace resources in Kubernetes. type NamespaceClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.Namespace) (*v1.Namespace, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.Namespace) (*v1.Namespace, error) + // UpdateStatus updates the Status field of a the object and return the newly updated Object or an error. + // Will always return an error if the object does not have a status field. UpdateStatus(*v1.Namespace) (*v1.Namespace, error) + + // Delete deletes the Object in the given name. Delete(name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(name string, options metav1.GetOptions) (*v1.Namespace, error) + + // List will attempt to find multiple resources. List(opts metav1.ListOptions) (*v1.NamespaceList, error) + + // Watch will start watching resources. Watch(opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Namespace, err error) } +// NamespaceCache interface for retrieving Namespace resources in memory. type NamespaceCache interface { + // Get returns the resources with the specified name from the cache. Get(name string) (*v1.Namespace, error) + + // List will attempt to find resources from the Cache. List(selector labels.Selector) ([]*v1.Namespace, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer NamespaceIndexer) - GetByIndex(indexName, key string) ([]*v1.Namespace, error) -} - -type NamespaceIndexer func(obj *v1.Namespace) ([]string, error) - -type namespaceController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewNamespaceController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) NamespaceController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &namespaceController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromNamespaceHandlerToHandler(sync NamespaceHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.Namespace - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.Namespace)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *namespaceController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.Namespace)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateNamespaceDeepCopyOnChange(client NamespaceClient, obj *v1.Namespace, handler func(obj *v1.Namespace) (*v1.Namespace, error)) (*v1.Namespace, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *namespaceController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} - -func (c *namespaceController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *namespaceController) OnChange(ctx context.Context, name string, sync NamespaceHandler) { - c.AddGenericHandler(ctx, name, FromNamespaceHandlerToHandler(sync)) -} - -func (c *namespaceController) OnRemove(ctx context.Context, name string, sync NamespaceHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromNamespaceHandlerToHandler(sync))) -} - -func (c *namespaceController) Enqueue(name string) { - c.controller.Enqueue("", name) -} - -func (c *namespaceController) EnqueueAfter(name string, duration time.Duration) { - c.controller.EnqueueAfter("", name, duration) -} - -func (c *namespaceController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *namespaceController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *namespaceController) Cache() NamespaceCache { - return &namespaceCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *namespaceController) Create(obj *v1.Namespace) (*v1.Namespace, error) { - result := &v1.Namespace{} - return result, c.client.Create(context.TODO(), "", obj, result, metav1.CreateOptions{}) -} - -func (c *namespaceController) Update(obj *v1.Namespace) (*v1.Namespace, error) { - result := &v1.Namespace{} - return result, c.client.Update(context.TODO(), "", obj, result, metav1.UpdateOptions{}) -} - -func (c *namespaceController) UpdateStatus(obj *v1.Namespace) (*v1.Namespace, error) { - result := &v1.Namespace{} - return result, c.client.UpdateStatus(context.TODO(), "", obj, result, metav1.UpdateOptions{}) -} -func (c *namespaceController) Delete(name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), "", name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.Namespace, error) } -func (c *namespaceController) Get(name string, options metav1.GetOptions) (*v1.Namespace, error) { - result := &v1.Namespace{} - return result, c.client.Get(context.TODO(), "", name, result, options) -} +// NamespaceHandler is function for performing any potential modifications to a Namespace resource. +type NamespaceHandler func(string, *v1.Namespace) (*v1.Namespace, error) -func (c *namespaceController) List(opts metav1.ListOptions) (*v1.NamespaceList, error) { - result := &v1.NamespaceList{} - return result, c.client.List(context.TODO(), "", result, opts) -} +// NamespaceIndexer computes a set of indexed values for the provided object. +type NamespaceIndexer func(obj *v1.Namespace) ([]string, error) -func (c *namespaceController) Watch(opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), "", opts) +// NamespaceGenericController wraps wrangler/pkg/generic.NonNamespacedController so that the function definitions adhere to NamespaceController interface. +type NamespaceGenericController struct { + generic.NonNamespacedControllerInterface[*v1.Namespace, *v1.NamespaceList] } -func (c *namespaceController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Namespace, error) { - result := &v1.Namespace{} - return result, c.client.Patch(context.TODO(), "", name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *NamespaceGenericController) OnChange(ctx context.Context, name string, sync NamespaceHandler) { + c.NonNamespacedControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.Namespace](sync)) } -type namespaceCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *NamespaceGenericController) OnRemove(ctx context.Context, name string, sync NamespaceHandler) { + c.NonNamespacedControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.Namespace](sync)) } -func (c *namespaceCache) Get(name string) (*v1.Namespace, error) { - obj, exists, err := c.indexer.GetByKey(name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *NamespaceGenericController) Cache() NamespaceCache { + return &NamespaceGenericCache{ + c.NonNamespacedControllerInterface.Cache(), } - return obj.(*v1.Namespace), nil } -func (c *namespaceCache) List(selector labels.Selector) (ret []*v1.Namespace, err error) { - - err = cache.ListAll(c.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1.Namespace)) - }) - - return ret, err +// NamespaceGenericCache wraps wrangler/pkg/generic.NonNamespacedCache so the function definitions adhere to NamespaceCache interface. +type NamespaceGenericCache struct { + generic.NonNamespacedCacheInterface[*v1.Namespace] } -func (c *namespaceCache) AddIndexer(indexName string, indexer NamespaceIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.Namespace)) - }, - })) -} - -func (c *namespaceCache) GetByIndex(indexName, key string) (result []*v1.Namespace, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.Namespace, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.Namespace)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c NamespaceGenericCache) AddIndexer(indexName string, indexer NamespaceIndexer) { + c.NonNamespacedCacheInterface.AddIndexer(indexName, generic.Indexer[*v1.Namespace](indexer)) } type NamespaceStatusHandler func(obj *v1.Namespace, status v1.NamespaceStatus) (v1.NamespaceStatus, error) type NamespaceGeneratingHandler func(obj *v1.Namespace, status v1.NamespaceStatus) ([]runtime.Object, v1.NamespaceStatus, error) +func FromNamespaceHandlerToHandler(sync NamespaceHandler) generic.Handler { + return generic.FromObjectHandlerToHandler(generic.ObjectHandler[*v1.Namespace](sync)) +} + func RegisterNamespaceStatusHandler(ctx context.Context, controller NamespaceController, condition condition.Cond, name string, handler NamespaceStatusHandler) { statusHandler := &namespaceStatusHandler{ client: controller, diff --git a/pkg/generated/controllers/core/v1/node.go b/pkg/generated/controllers/core/v1/node.go index b444b33c..277fcc67 100644 --- a/pkg/generated/controllers/core/v1/node.go +++ b/pkg/generated/controllers/core/v1/node.go @@ -22,8 +22,6 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,237 +34,121 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type NodeHandler func(string, *v1.Node) (*v1.Node, error) - +// NodeController interface for managing Node resources. type NodeController interface { generic.ControllerMeta NodeClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync NodeHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync NodeHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() NodeCache } +// NodeClient interface for managing Node resources in Kubernetes. type NodeClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.Node) (*v1.Node, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.Node) (*v1.Node, error) + // UpdateStatus updates the Status field of a the object and return the newly updated Object or an error. + // Will always return an error if the object does not have a status field. UpdateStatus(*v1.Node) (*v1.Node, error) + + // Delete deletes the Object in the given name. Delete(name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(name string, options metav1.GetOptions) (*v1.Node, error) + + // List will attempt to find multiple resources. List(opts metav1.ListOptions) (*v1.NodeList, error) + + // Watch will start watching resources. Watch(opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Node, err error) } +// NodeCache interface for retrieving Node resources in memory. type NodeCache interface { + // Get returns the resources with the specified name from the cache. Get(name string) (*v1.Node, error) + + // List will attempt to find resources from the Cache. List(selector labels.Selector) ([]*v1.Node, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer NodeIndexer) - GetByIndex(indexName, key string) ([]*v1.Node, error) -} - -type NodeIndexer func(obj *v1.Node) ([]string, error) - -type nodeController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewNodeController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) NodeController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &nodeController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromNodeHandlerToHandler(sync NodeHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.Node - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.Node)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *nodeController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.Node)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateNodeDeepCopyOnChange(client NodeClient, obj *v1.Node, handler func(obj *v1.Node) (*v1.Node, error)) (*v1.Node, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *nodeController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} - -func (c *nodeController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *nodeController) OnChange(ctx context.Context, name string, sync NodeHandler) { - c.AddGenericHandler(ctx, name, FromNodeHandlerToHandler(sync)) -} - -func (c *nodeController) OnRemove(ctx context.Context, name string, sync NodeHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromNodeHandlerToHandler(sync))) -} - -func (c *nodeController) Enqueue(name string) { - c.controller.Enqueue("", name) -} - -func (c *nodeController) EnqueueAfter(name string, duration time.Duration) { - c.controller.EnqueueAfter("", name, duration) -} - -func (c *nodeController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *nodeController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *nodeController) Cache() NodeCache { - return &nodeCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *nodeController) Create(obj *v1.Node) (*v1.Node, error) { - result := &v1.Node{} - return result, c.client.Create(context.TODO(), "", obj, result, metav1.CreateOptions{}) -} - -func (c *nodeController) Update(obj *v1.Node) (*v1.Node, error) { - result := &v1.Node{} - return result, c.client.Update(context.TODO(), "", obj, result, metav1.UpdateOptions{}) -} - -func (c *nodeController) UpdateStatus(obj *v1.Node) (*v1.Node, error) { - result := &v1.Node{} - return result, c.client.UpdateStatus(context.TODO(), "", obj, result, metav1.UpdateOptions{}) -} -func (c *nodeController) Delete(name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), "", name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.Node, error) } -func (c *nodeController) Get(name string, options metav1.GetOptions) (*v1.Node, error) { - result := &v1.Node{} - return result, c.client.Get(context.TODO(), "", name, result, options) -} +// NodeHandler is function for performing any potential modifications to a Node resource. +type NodeHandler func(string, *v1.Node) (*v1.Node, error) -func (c *nodeController) List(opts metav1.ListOptions) (*v1.NodeList, error) { - result := &v1.NodeList{} - return result, c.client.List(context.TODO(), "", result, opts) -} +// NodeIndexer computes a set of indexed values for the provided object. +type NodeIndexer func(obj *v1.Node) ([]string, error) -func (c *nodeController) Watch(opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), "", opts) +// NodeGenericController wraps wrangler/pkg/generic.NonNamespacedController so that the function definitions adhere to NodeController interface. +type NodeGenericController struct { + generic.NonNamespacedControllerInterface[*v1.Node, *v1.NodeList] } -func (c *nodeController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Node, error) { - result := &v1.Node{} - return result, c.client.Patch(context.TODO(), "", name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *NodeGenericController) OnChange(ctx context.Context, name string, sync NodeHandler) { + c.NonNamespacedControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.Node](sync)) } -type nodeCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *NodeGenericController) OnRemove(ctx context.Context, name string, sync NodeHandler) { + c.NonNamespacedControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.Node](sync)) } -func (c *nodeCache) Get(name string) (*v1.Node, error) { - obj, exists, err := c.indexer.GetByKey(name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *NodeGenericController) Cache() NodeCache { + return &NodeGenericCache{ + c.NonNamespacedControllerInterface.Cache(), } - return obj.(*v1.Node), nil } -func (c *nodeCache) List(selector labels.Selector) (ret []*v1.Node, err error) { - - err = cache.ListAll(c.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1.Node)) - }) - - return ret, err +// NodeGenericCache wraps wrangler/pkg/generic.NonNamespacedCache so the function definitions adhere to NodeCache interface. +type NodeGenericCache struct { + generic.NonNamespacedCacheInterface[*v1.Node] } -func (c *nodeCache) AddIndexer(indexName string, indexer NodeIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.Node)) - }, - })) -} - -func (c *nodeCache) GetByIndex(indexName, key string) (result []*v1.Node, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.Node, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.Node)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c NodeGenericCache) AddIndexer(indexName string, indexer NodeIndexer) { + c.NonNamespacedCacheInterface.AddIndexer(indexName, generic.Indexer[*v1.Node](indexer)) } type NodeStatusHandler func(obj *v1.Node, status v1.NodeStatus) (v1.NodeStatus, error) type NodeGeneratingHandler func(obj *v1.Node, status v1.NodeStatus) ([]runtime.Object, v1.NodeStatus, error) +func FromNodeHandlerToHandler(sync NodeHandler) generic.Handler { + return generic.FromObjectHandlerToHandler(generic.ObjectHandler[*v1.Node](sync)) +} + func RegisterNodeStatusHandler(ctx context.Context, controller NodeController, condition condition.Cond, name string, handler NodeStatusHandler) { statusHandler := &nodeStatusHandler{ client: controller, diff --git a/pkg/generated/controllers/core/v1/persistentvolume.go b/pkg/generated/controllers/core/v1/persistentvolume.go index 576c5607..726fbdf7 100644 --- a/pkg/generated/controllers/core/v1/persistentvolume.go +++ b/pkg/generated/controllers/core/v1/persistentvolume.go @@ -22,8 +22,6 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,237 +34,121 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type PersistentVolumeHandler func(string, *v1.PersistentVolume) (*v1.PersistentVolume, error) - +// PersistentVolumeController interface for managing PersistentVolume resources. type PersistentVolumeController interface { generic.ControllerMeta PersistentVolumeClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync PersistentVolumeHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync PersistentVolumeHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() PersistentVolumeCache } +// PersistentVolumeClient interface for managing PersistentVolume resources in Kubernetes. type PersistentVolumeClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.PersistentVolume) (*v1.PersistentVolume, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.PersistentVolume) (*v1.PersistentVolume, error) + // UpdateStatus updates the Status field of a the object and return the newly updated Object or an error. + // Will always return an error if the object does not have a status field. UpdateStatus(*v1.PersistentVolume) (*v1.PersistentVolume, error) + + // Delete deletes the Object in the given name. Delete(name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(name string, options metav1.GetOptions) (*v1.PersistentVolume, error) + + // List will attempt to find multiple resources. List(opts metav1.ListOptions) (*v1.PersistentVolumeList, error) + + // Watch will start watching resources. Watch(opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.PersistentVolume, err error) } +// PersistentVolumeCache interface for retrieving PersistentVolume resources in memory. type PersistentVolumeCache interface { + // Get returns the resources with the specified name from the cache. Get(name string) (*v1.PersistentVolume, error) + + // List will attempt to find resources from the Cache. List(selector labels.Selector) ([]*v1.PersistentVolume, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer PersistentVolumeIndexer) - GetByIndex(indexName, key string) ([]*v1.PersistentVolume, error) -} - -type PersistentVolumeIndexer func(obj *v1.PersistentVolume) ([]string, error) - -type persistentVolumeController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewPersistentVolumeController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) PersistentVolumeController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &persistentVolumeController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromPersistentVolumeHandlerToHandler(sync PersistentVolumeHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.PersistentVolume - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.PersistentVolume)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *persistentVolumeController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.PersistentVolume)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdatePersistentVolumeDeepCopyOnChange(client PersistentVolumeClient, obj *v1.PersistentVolume, handler func(obj *v1.PersistentVolume) (*v1.PersistentVolume, error)) (*v1.PersistentVolume, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *persistentVolumeController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} - -func (c *persistentVolumeController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *persistentVolumeController) OnChange(ctx context.Context, name string, sync PersistentVolumeHandler) { - c.AddGenericHandler(ctx, name, FromPersistentVolumeHandlerToHandler(sync)) -} - -func (c *persistentVolumeController) OnRemove(ctx context.Context, name string, sync PersistentVolumeHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromPersistentVolumeHandlerToHandler(sync))) -} - -func (c *persistentVolumeController) Enqueue(name string) { - c.controller.Enqueue("", name) -} - -func (c *persistentVolumeController) EnqueueAfter(name string, duration time.Duration) { - c.controller.EnqueueAfter("", name, duration) -} - -func (c *persistentVolumeController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *persistentVolumeController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *persistentVolumeController) Cache() PersistentVolumeCache { - return &persistentVolumeCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *persistentVolumeController) Create(obj *v1.PersistentVolume) (*v1.PersistentVolume, error) { - result := &v1.PersistentVolume{} - return result, c.client.Create(context.TODO(), "", obj, result, metav1.CreateOptions{}) -} - -func (c *persistentVolumeController) Update(obj *v1.PersistentVolume) (*v1.PersistentVolume, error) { - result := &v1.PersistentVolume{} - return result, c.client.Update(context.TODO(), "", obj, result, metav1.UpdateOptions{}) -} - -func (c *persistentVolumeController) UpdateStatus(obj *v1.PersistentVolume) (*v1.PersistentVolume, error) { - result := &v1.PersistentVolume{} - return result, c.client.UpdateStatus(context.TODO(), "", obj, result, metav1.UpdateOptions{}) -} -func (c *persistentVolumeController) Delete(name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), "", name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.PersistentVolume, error) } -func (c *persistentVolumeController) Get(name string, options metav1.GetOptions) (*v1.PersistentVolume, error) { - result := &v1.PersistentVolume{} - return result, c.client.Get(context.TODO(), "", name, result, options) -} +// PersistentVolumeHandler is function for performing any potential modifications to a PersistentVolume resource. +type PersistentVolumeHandler func(string, *v1.PersistentVolume) (*v1.PersistentVolume, error) -func (c *persistentVolumeController) List(opts metav1.ListOptions) (*v1.PersistentVolumeList, error) { - result := &v1.PersistentVolumeList{} - return result, c.client.List(context.TODO(), "", result, opts) -} +// PersistentVolumeIndexer computes a set of indexed values for the provided object. +type PersistentVolumeIndexer func(obj *v1.PersistentVolume) ([]string, error) -func (c *persistentVolumeController) Watch(opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), "", opts) +// PersistentVolumeGenericController wraps wrangler/pkg/generic.NonNamespacedController so that the function definitions adhere to PersistentVolumeController interface. +type PersistentVolumeGenericController struct { + generic.NonNamespacedControllerInterface[*v1.PersistentVolume, *v1.PersistentVolumeList] } -func (c *persistentVolumeController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v1.PersistentVolume, error) { - result := &v1.PersistentVolume{} - return result, c.client.Patch(context.TODO(), "", name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *PersistentVolumeGenericController) OnChange(ctx context.Context, name string, sync PersistentVolumeHandler) { + c.NonNamespacedControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.PersistentVolume](sync)) } -type persistentVolumeCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *PersistentVolumeGenericController) OnRemove(ctx context.Context, name string, sync PersistentVolumeHandler) { + c.NonNamespacedControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.PersistentVolume](sync)) } -func (c *persistentVolumeCache) Get(name string) (*v1.PersistentVolume, error) { - obj, exists, err := c.indexer.GetByKey(name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *PersistentVolumeGenericController) Cache() PersistentVolumeCache { + return &PersistentVolumeGenericCache{ + c.NonNamespacedControllerInterface.Cache(), } - return obj.(*v1.PersistentVolume), nil } -func (c *persistentVolumeCache) List(selector labels.Selector) (ret []*v1.PersistentVolume, err error) { - - err = cache.ListAll(c.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1.PersistentVolume)) - }) - - return ret, err +// PersistentVolumeGenericCache wraps wrangler/pkg/generic.NonNamespacedCache so the function definitions adhere to PersistentVolumeCache interface. +type PersistentVolumeGenericCache struct { + generic.NonNamespacedCacheInterface[*v1.PersistentVolume] } -func (c *persistentVolumeCache) AddIndexer(indexName string, indexer PersistentVolumeIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.PersistentVolume)) - }, - })) -} - -func (c *persistentVolumeCache) GetByIndex(indexName, key string) (result []*v1.PersistentVolume, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.PersistentVolume, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.PersistentVolume)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c PersistentVolumeGenericCache) AddIndexer(indexName string, indexer PersistentVolumeIndexer) { + c.NonNamespacedCacheInterface.AddIndexer(indexName, generic.Indexer[*v1.PersistentVolume](indexer)) } type PersistentVolumeStatusHandler func(obj *v1.PersistentVolume, status v1.PersistentVolumeStatus) (v1.PersistentVolumeStatus, error) type PersistentVolumeGeneratingHandler func(obj *v1.PersistentVolume, status v1.PersistentVolumeStatus) ([]runtime.Object, v1.PersistentVolumeStatus, error) +func FromPersistentVolumeHandlerToHandler(sync PersistentVolumeHandler) generic.Handler { + return generic.FromObjectHandlerToHandler(generic.ObjectHandler[*v1.PersistentVolume](sync)) +} + func RegisterPersistentVolumeStatusHandler(ctx context.Context, controller PersistentVolumeController, condition condition.Cond, name string, handler PersistentVolumeStatusHandler) { statusHandler := &persistentVolumeStatusHandler{ client: controller, diff --git a/pkg/generated/controllers/core/v1/persistentvolumeclaim.go b/pkg/generated/controllers/core/v1/persistentvolumeclaim.go index 5fbce6d8..dda6cd86 100644 --- a/pkg/generated/controllers/core/v1/persistentvolumeclaim.go +++ b/pkg/generated/controllers/core/v1/persistentvolumeclaim.go @@ -22,8 +22,6 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,237 +34,121 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type PersistentVolumeClaimHandler func(string, *v1.PersistentVolumeClaim) (*v1.PersistentVolumeClaim, error) - +// PersistentVolumeClaimController interface for managing PersistentVolumeClaim resources. type PersistentVolumeClaimController interface { generic.ControllerMeta PersistentVolumeClaimClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync PersistentVolumeClaimHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync PersistentVolumeClaimHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(namespace, name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() PersistentVolumeClaimCache } +// PersistentVolumeClaimClient interface for managing PersistentVolumeClaim resources in Kubernetes. type PersistentVolumeClaimClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.PersistentVolumeClaim) (*v1.PersistentVolumeClaim, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.PersistentVolumeClaim) (*v1.PersistentVolumeClaim, error) + // UpdateStatus updates the Status field of a the object and return the newly updated Object or an error. + // Will always return an error if the object does not have a status field. UpdateStatus(*v1.PersistentVolumeClaim) (*v1.PersistentVolumeClaim, error) + + // Delete deletes the Object in the given name. Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(namespace, name string, options metav1.GetOptions) (*v1.PersistentVolumeClaim, error) + + // List will attempt to find multiple resources. List(namespace string, opts metav1.ListOptions) (*v1.PersistentVolumeClaimList, error) + + // Watch will start watching resources. Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.PersistentVolumeClaim, err error) } +// PersistentVolumeClaimCache interface for retrieving PersistentVolumeClaim resources in memory. type PersistentVolumeClaimCache interface { + // Get returns the resources with the specified name from the cache. Get(namespace, name string) (*v1.PersistentVolumeClaim, error) + + // List will attempt to find resources from the Cache. List(namespace string, selector labels.Selector) ([]*v1.PersistentVolumeClaim, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer PersistentVolumeClaimIndexer) - GetByIndex(indexName, key string) ([]*v1.PersistentVolumeClaim, error) -} - -type PersistentVolumeClaimIndexer func(obj *v1.PersistentVolumeClaim) ([]string, error) - -type persistentVolumeClaimController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewPersistentVolumeClaimController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) PersistentVolumeClaimController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &persistentVolumeClaimController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromPersistentVolumeClaimHandlerToHandler(sync PersistentVolumeClaimHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.PersistentVolumeClaim - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.PersistentVolumeClaim)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *persistentVolumeClaimController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.PersistentVolumeClaim)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdatePersistentVolumeClaimDeepCopyOnChange(client PersistentVolumeClaimClient, obj *v1.PersistentVolumeClaim, handler func(obj *v1.PersistentVolumeClaim) (*v1.PersistentVolumeClaim, error)) (*v1.PersistentVolumeClaim, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *persistentVolumeClaimController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} - -func (c *persistentVolumeClaimController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *persistentVolumeClaimController) OnChange(ctx context.Context, name string, sync PersistentVolumeClaimHandler) { - c.AddGenericHandler(ctx, name, FromPersistentVolumeClaimHandlerToHandler(sync)) -} - -func (c *persistentVolumeClaimController) OnRemove(ctx context.Context, name string, sync PersistentVolumeClaimHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromPersistentVolumeClaimHandlerToHandler(sync))) -} - -func (c *persistentVolumeClaimController) Enqueue(namespace, name string) { - c.controller.Enqueue(namespace, name) -} - -func (c *persistentVolumeClaimController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controller.EnqueueAfter(namespace, name, duration) -} - -func (c *persistentVolumeClaimController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *persistentVolumeClaimController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *persistentVolumeClaimController) Cache() PersistentVolumeClaimCache { - return &persistentVolumeClaimCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *persistentVolumeClaimController) Create(obj *v1.PersistentVolumeClaim) (*v1.PersistentVolumeClaim, error) { - result := &v1.PersistentVolumeClaim{} - return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) -} - -func (c *persistentVolumeClaimController) Update(obj *v1.PersistentVolumeClaim) (*v1.PersistentVolumeClaim, error) { - result := &v1.PersistentVolumeClaim{} - return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} - -func (c *persistentVolumeClaimController) UpdateStatus(obj *v1.PersistentVolumeClaim) (*v1.PersistentVolumeClaim, error) { - result := &v1.PersistentVolumeClaim{} - return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} -func (c *persistentVolumeClaimController) Delete(namespace, name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), namespace, name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.PersistentVolumeClaim, error) } -func (c *persistentVolumeClaimController) Get(namespace, name string, options metav1.GetOptions) (*v1.PersistentVolumeClaim, error) { - result := &v1.PersistentVolumeClaim{} - return result, c.client.Get(context.TODO(), namespace, name, result, options) -} +// PersistentVolumeClaimHandler is function for performing any potential modifications to a PersistentVolumeClaim resource. +type PersistentVolumeClaimHandler func(string, *v1.PersistentVolumeClaim) (*v1.PersistentVolumeClaim, error) -func (c *persistentVolumeClaimController) List(namespace string, opts metav1.ListOptions) (*v1.PersistentVolumeClaimList, error) { - result := &v1.PersistentVolumeClaimList{} - return result, c.client.List(context.TODO(), namespace, result, opts) -} +// PersistentVolumeClaimIndexer computes a set of indexed values for the provided object. +type PersistentVolumeClaimIndexer func(obj *v1.PersistentVolumeClaim) ([]string, error) -func (c *persistentVolumeClaimController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), namespace, opts) +// PersistentVolumeClaimGenericController wraps wrangler/pkg/generic.Controller so that the function definitions adhere to PersistentVolumeClaimController interface. +type PersistentVolumeClaimGenericController struct { + generic.ControllerInterface[*v1.PersistentVolumeClaim, *v1.PersistentVolumeClaimList] } -func (c *persistentVolumeClaimController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.PersistentVolumeClaim, error) { - result := &v1.PersistentVolumeClaim{} - return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *PersistentVolumeClaimGenericController) OnChange(ctx context.Context, name string, sync PersistentVolumeClaimHandler) { + c.ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.PersistentVolumeClaim](sync)) } -type persistentVolumeClaimCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *PersistentVolumeClaimGenericController) OnRemove(ctx context.Context, name string, sync PersistentVolumeClaimHandler) { + c.ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.PersistentVolumeClaim](sync)) } -func (c *persistentVolumeClaimCache) Get(namespace, name string) (*v1.PersistentVolumeClaim, error) { - obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *PersistentVolumeClaimGenericController) Cache() PersistentVolumeClaimCache { + return &PersistentVolumeClaimGenericCache{ + c.ControllerInterface.Cache(), } - return obj.(*v1.PersistentVolumeClaim), nil } -func (c *persistentVolumeClaimCache) List(namespace string, selector labels.Selector) (ret []*v1.PersistentVolumeClaim, err error) { - - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.PersistentVolumeClaim)) - }) - - return ret, err +// PersistentVolumeClaimGenericCache wraps wrangler/pkg/generic.Cache so the function definitions adhere to PersistentVolumeClaimCache interface. +type PersistentVolumeClaimGenericCache struct { + generic.CacheInterface[*v1.PersistentVolumeClaim] } -func (c *persistentVolumeClaimCache) AddIndexer(indexName string, indexer PersistentVolumeClaimIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.PersistentVolumeClaim)) - }, - })) -} - -func (c *persistentVolumeClaimCache) GetByIndex(indexName, key string) (result []*v1.PersistentVolumeClaim, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.PersistentVolumeClaim, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.PersistentVolumeClaim)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c PersistentVolumeClaimGenericCache) AddIndexer(indexName string, indexer PersistentVolumeClaimIndexer) { + c.CacheInterface.AddIndexer(indexName, generic.Indexer[*v1.PersistentVolumeClaim](indexer)) } type PersistentVolumeClaimStatusHandler func(obj *v1.PersistentVolumeClaim, status v1.PersistentVolumeClaimStatus) (v1.PersistentVolumeClaimStatus, error) type PersistentVolumeClaimGeneratingHandler func(obj *v1.PersistentVolumeClaim, status v1.PersistentVolumeClaimStatus) ([]runtime.Object, v1.PersistentVolumeClaimStatus, error) +func FromPersistentVolumeClaimHandlerToHandler(sync PersistentVolumeClaimHandler) generic.Handler { + return generic.FromObjectHandlerToHandler(generic.ObjectHandler[*v1.PersistentVolumeClaim](sync)) +} + func RegisterPersistentVolumeClaimStatusHandler(ctx context.Context, controller PersistentVolumeClaimController, condition condition.Cond, name string, handler PersistentVolumeClaimStatusHandler) { statusHandler := &persistentVolumeClaimStatusHandler{ client: controller, diff --git a/pkg/generated/controllers/core/v1/pod.go b/pkg/generated/controllers/core/v1/pod.go index 4286bcf5..ce6b9aa9 100644 --- a/pkg/generated/controllers/core/v1/pod.go +++ b/pkg/generated/controllers/core/v1/pod.go @@ -22,8 +22,6 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,237 +34,121 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type PodHandler func(string, *v1.Pod) (*v1.Pod, error) - +// PodController interface for managing Pod resources. type PodController interface { generic.ControllerMeta PodClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync PodHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync PodHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(namespace, name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() PodCache } +// PodClient interface for managing Pod resources in Kubernetes. type PodClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.Pod) (*v1.Pod, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.Pod) (*v1.Pod, error) + // UpdateStatus updates the Status field of a the object and return the newly updated Object or an error. + // Will always return an error if the object does not have a status field. UpdateStatus(*v1.Pod) (*v1.Pod, error) + + // Delete deletes the Object in the given name. Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(namespace, name string, options metav1.GetOptions) (*v1.Pod, error) + + // List will attempt to find multiple resources. List(namespace string, opts metav1.ListOptions) (*v1.PodList, error) + + // Watch will start watching resources. Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Pod, err error) } +// PodCache interface for retrieving Pod resources in memory. type PodCache interface { + // Get returns the resources with the specified name from the cache. Get(namespace, name string) (*v1.Pod, error) + + // List will attempt to find resources from the Cache. List(namespace string, selector labels.Selector) ([]*v1.Pod, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer PodIndexer) - GetByIndex(indexName, key string) ([]*v1.Pod, error) -} - -type PodIndexer func(obj *v1.Pod) ([]string, error) - -type podController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewPodController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) PodController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &podController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromPodHandlerToHandler(sync PodHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.Pod - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.Pod)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *podController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.Pod)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdatePodDeepCopyOnChange(client PodClient, obj *v1.Pod, handler func(obj *v1.Pod) (*v1.Pod, error)) (*v1.Pod, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *podController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} - -func (c *podController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *podController) OnChange(ctx context.Context, name string, sync PodHandler) { - c.AddGenericHandler(ctx, name, FromPodHandlerToHandler(sync)) -} - -func (c *podController) OnRemove(ctx context.Context, name string, sync PodHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromPodHandlerToHandler(sync))) -} - -func (c *podController) Enqueue(namespace, name string) { - c.controller.Enqueue(namespace, name) -} - -func (c *podController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controller.EnqueueAfter(namespace, name, duration) -} - -func (c *podController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *podController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *podController) Cache() PodCache { - return &podCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *podController) Create(obj *v1.Pod) (*v1.Pod, error) { - result := &v1.Pod{} - return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) -} - -func (c *podController) Update(obj *v1.Pod) (*v1.Pod, error) { - result := &v1.Pod{} - return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} - -func (c *podController) UpdateStatus(obj *v1.Pod) (*v1.Pod, error) { - result := &v1.Pod{} - return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} -func (c *podController) Delete(namespace, name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), namespace, name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.Pod, error) } -func (c *podController) Get(namespace, name string, options metav1.GetOptions) (*v1.Pod, error) { - result := &v1.Pod{} - return result, c.client.Get(context.TODO(), namespace, name, result, options) -} +// PodHandler is function for performing any potential modifications to a Pod resource. +type PodHandler func(string, *v1.Pod) (*v1.Pod, error) -func (c *podController) List(namespace string, opts metav1.ListOptions) (*v1.PodList, error) { - result := &v1.PodList{} - return result, c.client.List(context.TODO(), namespace, result, opts) -} +// PodIndexer computes a set of indexed values for the provided object. +type PodIndexer func(obj *v1.Pod) ([]string, error) -func (c *podController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), namespace, opts) +// PodGenericController wraps wrangler/pkg/generic.Controller so that the function definitions adhere to PodController interface. +type PodGenericController struct { + generic.ControllerInterface[*v1.Pod, *v1.PodList] } -func (c *podController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Pod, error) { - result := &v1.Pod{} - return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *PodGenericController) OnChange(ctx context.Context, name string, sync PodHandler) { + c.ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.Pod](sync)) } -type podCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *PodGenericController) OnRemove(ctx context.Context, name string, sync PodHandler) { + c.ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.Pod](sync)) } -func (c *podCache) Get(namespace, name string) (*v1.Pod, error) { - obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *PodGenericController) Cache() PodCache { + return &PodGenericCache{ + c.ControllerInterface.Cache(), } - return obj.(*v1.Pod), nil } -func (c *podCache) List(namespace string, selector labels.Selector) (ret []*v1.Pod, err error) { - - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.Pod)) - }) - - return ret, err +// PodGenericCache wraps wrangler/pkg/generic.Cache so the function definitions adhere to PodCache interface. +type PodGenericCache struct { + generic.CacheInterface[*v1.Pod] } -func (c *podCache) AddIndexer(indexName string, indexer PodIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.Pod)) - }, - })) -} - -func (c *podCache) GetByIndex(indexName, key string) (result []*v1.Pod, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.Pod, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.Pod)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c PodGenericCache) AddIndexer(indexName string, indexer PodIndexer) { + c.CacheInterface.AddIndexer(indexName, generic.Indexer[*v1.Pod](indexer)) } type PodStatusHandler func(obj *v1.Pod, status v1.PodStatus) (v1.PodStatus, error) type PodGeneratingHandler func(obj *v1.Pod, status v1.PodStatus) ([]runtime.Object, v1.PodStatus, error) +func FromPodHandlerToHandler(sync PodHandler) generic.Handler { + return generic.FromObjectHandlerToHandler(generic.ObjectHandler[*v1.Pod](sync)) +} + func RegisterPodStatusHandler(ctx context.Context, controller PodController, condition condition.Cond, name string, handler PodStatusHandler) { statusHandler := &podStatusHandler{ client: controller, diff --git a/pkg/generated/controllers/core/v1/secret.go b/pkg/generated/controllers/core/v1/secret.go index 55cc6370..38e9f06c 100644 --- a/pkg/generated/controllers/core/v1/secret.go +++ b/pkg/generated/controllers/core/v1/secret.go @@ -22,235 +22,111 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type SecretHandler func(string, *v1.Secret) (*v1.Secret, error) - +// SecretController interface for managing Secret resources. type SecretController interface { generic.ControllerMeta SecretClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync SecretHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync SecretHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(namespace, name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() SecretCache } +// SecretClient interface for managing Secret resources in Kubernetes. type SecretClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.Secret) (*v1.Secret, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.Secret) (*v1.Secret, error) + // Delete deletes the Object in the given name. Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(namespace, name string, options metav1.GetOptions) (*v1.Secret, error) + + // List will attempt to find multiple resources. List(namespace string, opts metav1.ListOptions) (*v1.SecretList, error) + + // Watch will start watching resources. Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Secret, err error) } +// SecretCache interface for retrieving Secret resources in memory. type SecretCache interface { + // Get returns the resources with the specified name from the cache. Get(namespace, name string) (*v1.Secret, error) + + // List will attempt to find resources from the Cache. List(namespace string, selector labels.Selector) ([]*v1.Secret, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer SecretIndexer) - GetByIndex(indexName, key string) ([]*v1.Secret, error) -} - -type SecretIndexer func(obj *v1.Secret) ([]string, error) - -type secretController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewSecretController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) SecretController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &secretController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromSecretHandlerToHandler(sync SecretHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.Secret - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.Secret)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *secretController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.Secret)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateSecretDeepCopyOnChange(client SecretClient, obj *v1.Secret, handler func(obj *v1.Secret) (*v1.Secret, error)) (*v1.Secret, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *secretController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} -func (c *secretController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *secretController) OnChange(ctx context.Context, name string, sync SecretHandler) { - c.AddGenericHandler(ctx, name, FromSecretHandlerToHandler(sync)) -} - -func (c *secretController) OnRemove(ctx context.Context, name string, sync SecretHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromSecretHandlerToHandler(sync))) -} - -func (c *secretController) Enqueue(namespace, name string) { - c.controller.Enqueue(namespace, name) -} - -func (c *secretController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controller.EnqueueAfter(namespace, name, duration) -} - -func (c *secretController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *secretController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *secretController) Cache() SecretCache { - return &secretCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *secretController) Create(obj *v1.Secret) (*v1.Secret, error) { - result := &v1.Secret{} - return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) -} - -func (c *secretController) Update(obj *v1.Secret) (*v1.Secret, error) { - result := &v1.Secret{} - return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} - -func (c *secretController) Delete(namespace, name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), namespace, name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.Secret, error) } -func (c *secretController) Get(namespace, name string, options metav1.GetOptions) (*v1.Secret, error) { - result := &v1.Secret{} - return result, c.client.Get(context.TODO(), namespace, name, result, options) -} +// SecretHandler is function for performing any potential modifications to a Secret resource. +type SecretHandler func(string, *v1.Secret) (*v1.Secret, error) -func (c *secretController) List(namespace string, opts metav1.ListOptions) (*v1.SecretList, error) { - result := &v1.SecretList{} - return result, c.client.List(context.TODO(), namespace, result, opts) -} +// SecretIndexer computes a set of indexed values for the provided object. +type SecretIndexer func(obj *v1.Secret) ([]string, error) -func (c *secretController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), namespace, opts) +// SecretGenericController wraps wrangler/pkg/generic.Controller so that the function definitions adhere to SecretController interface. +type SecretGenericController struct { + generic.ControllerInterface[*v1.Secret, *v1.SecretList] } -func (c *secretController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Secret, error) { - result := &v1.Secret{} - return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *SecretGenericController) OnChange(ctx context.Context, name string, sync SecretHandler) { + c.ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.Secret](sync)) } -type secretCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *SecretGenericController) OnRemove(ctx context.Context, name string, sync SecretHandler) { + c.ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.Secret](sync)) } -func (c *secretCache) Get(namespace, name string) (*v1.Secret, error) { - obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *SecretGenericController) Cache() SecretCache { + return &SecretGenericCache{ + c.ControllerInterface.Cache(), } - return obj.(*v1.Secret), nil -} - -func (c *secretCache) List(namespace string, selector labels.Selector) (ret []*v1.Secret, err error) { - - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.Secret)) - }) - - return ret, err } -func (c *secretCache) AddIndexer(indexName string, indexer SecretIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.Secret)) - }, - })) +// SecretGenericCache wraps wrangler/pkg/generic.Cache so the function definitions adhere to SecretCache interface. +type SecretGenericCache struct { + generic.CacheInterface[*v1.Secret] } -func (c *secretCache) GetByIndex(indexName, key string) (result []*v1.Secret, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.Secret, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.Secret)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c SecretGenericCache) AddIndexer(indexName string, indexer SecretIndexer) { + c.CacheInterface.AddIndexer(indexName, generic.Indexer[*v1.Secret](indexer)) } diff --git a/pkg/generated/controllers/core/v1/service.go b/pkg/generated/controllers/core/v1/service.go index 4802feb6..2003c274 100644 --- a/pkg/generated/controllers/core/v1/service.go +++ b/pkg/generated/controllers/core/v1/service.go @@ -22,8 +22,6 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,237 +34,121 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type ServiceHandler func(string, *v1.Service) (*v1.Service, error) - +// ServiceController interface for managing Service resources. type ServiceController interface { generic.ControllerMeta ServiceClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync ServiceHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync ServiceHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(namespace, name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() ServiceCache } +// ServiceClient interface for managing Service resources in Kubernetes. type ServiceClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.Service) (*v1.Service, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.Service) (*v1.Service, error) + // UpdateStatus updates the Status field of a the object and return the newly updated Object or an error. + // Will always return an error if the object does not have a status field. UpdateStatus(*v1.Service) (*v1.Service, error) + + // Delete deletes the Object in the given name. Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(namespace, name string, options metav1.GetOptions) (*v1.Service, error) + + // List will attempt to find multiple resources. List(namespace string, opts metav1.ListOptions) (*v1.ServiceList, error) + + // Watch will start watching resources. Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Service, err error) } +// ServiceCache interface for retrieving Service resources in memory. type ServiceCache interface { + // Get returns the resources with the specified name from the cache. Get(namespace, name string) (*v1.Service, error) + + // List will attempt to find resources from the Cache. List(namespace string, selector labels.Selector) ([]*v1.Service, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer ServiceIndexer) - GetByIndex(indexName, key string) ([]*v1.Service, error) -} - -type ServiceIndexer func(obj *v1.Service) ([]string, error) - -type serviceController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewServiceController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) ServiceController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &serviceController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromServiceHandlerToHandler(sync ServiceHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.Service - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.Service)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *serviceController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.Service)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateServiceDeepCopyOnChange(client ServiceClient, obj *v1.Service, handler func(obj *v1.Service) (*v1.Service, error)) (*v1.Service, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *serviceController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} - -func (c *serviceController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *serviceController) OnChange(ctx context.Context, name string, sync ServiceHandler) { - c.AddGenericHandler(ctx, name, FromServiceHandlerToHandler(sync)) -} - -func (c *serviceController) OnRemove(ctx context.Context, name string, sync ServiceHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromServiceHandlerToHandler(sync))) -} - -func (c *serviceController) Enqueue(namespace, name string) { - c.controller.Enqueue(namespace, name) -} - -func (c *serviceController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controller.EnqueueAfter(namespace, name, duration) -} - -func (c *serviceController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *serviceController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *serviceController) Cache() ServiceCache { - return &serviceCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *serviceController) Create(obj *v1.Service) (*v1.Service, error) { - result := &v1.Service{} - return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) -} - -func (c *serviceController) Update(obj *v1.Service) (*v1.Service, error) { - result := &v1.Service{} - return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} - -func (c *serviceController) UpdateStatus(obj *v1.Service) (*v1.Service, error) { - result := &v1.Service{} - return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} -func (c *serviceController) Delete(namespace, name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), namespace, name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.Service, error) } -func (c *serviceController) Get(namespace, name string, options metav1.GetOptions) (*v1.Service, error) { - result := &v1.Service{} - return result, c.client.Get(context.TODO(), namespace, name, result, options) -} +// ServiceHandler is function for performing any potential modifications to a Service resource. +type ServiceHandler func(string, *v1.Service) (*v1.Service, error) -func (c *serviceController) List(namespace string, opts metav1.ListOptions) (*v1.ServiceList, error) { - result := &v1.ServiceList{} - return result, c.client.List(context.TODO(), namespace, result, opts) -} +// ServiceIndexer computes a set of indexed values for the provided object. +type ServiceIndexer func(obj *v1.Service) ([]string, error) -func (c *serviceController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), namespace, opts) +// ServiceGenericController wraps wrangler/pkg/generic.Controller so that the function definitions adhere to ServiceController interface. +type ServiceGenericController struct { + generic.ControllerInterface[*v1.Service, *v1.ServiceList] } -func (c *serviceController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Service, error) { - result := &v1.Service{} - return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *ServiceGenericController) OnChange(ctx context.Context, name string, sync ServiceHandler) { + c.ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.Service](sync)) } -type serviceCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *ServiceGenericController) OnRemove(ctx context.Context, name string, sync ServiceHandler) { + c.ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.Service](sync)) } -func (c *serviceCache) Get(namespace, name string) (*v1.Service, error) { - obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *ServiceGenericController) Cache() ServiceCache { + return &ServiceGenericCache{ + c.ControllerInterface.Cache(), } - return obj.(*v1.Service), nil } -func (c *serviceCache) List(namespace string, selector labels.Selector) (ret []*v1.Service, err error) { - - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.Service)) - }) - - return ret, err +// ServiceGenericCache wraps wrangler/pkg/generic.Cache so the function definitions adhere to ServiceCache interface. +type ServiceGenericCache struct { + generic.CacheInterface[*v1.Service] } -func (c *serviceCache) AddIndexer(indexName string, indexer ServiceIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.Service)) - }, - })) -} - -func (c *serviceCache) GetByIndex(indexName, key string) (result []*v1.Service, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.Service, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.Service)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c ServiceGenericCache) AddIndexer(indexName string, indexer ServiceIndexer) { + c.CacheInterface.AddIndexer(indexName, generic.Indexer[*v1.Service](indexer)) } type ServiceStatusHandler func(obj *v1.Service, status v1.ServiceStatus) (v1.ServiceStatus, error) type ServiceGeneratingHandler func(obj *v1.Service, status v1.ServiceStatus) ([]runtime.Object, v1.ServiceStatus, error) +func FromServiceHandlerToHandler(sync ServiceHandler) generic.Handler { + return generic.FromObjectHandlerToHandler(generic.ObjectHandler[*v1.Service](sync)) +} + func RegisterServiceStatusHandler(ctx context.Context, controller ServiceController, condition condition.Cond, name string, handler ServiceStatusHandler) { statusHandler := &serviceStatusHandler{ client: controller, diff --git a/pkg/generated/controllers/core/v1/serviceaccount.go b/pkg/generated/controllers/core/v1/serviceaccount.go index f9a81cc8..752ebd32 100644 --- a/pkg/generated/controllers/core/v1/serviceaccount.go +++ b/pkg/generated/controllers/core/v1/serviceaccount.go @@ -22,235 +22,111 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type ServiceAccountHandler func(string, *v1.ServiceAccount) (*v1.ServiceAccount, error) - +// ServiceAccountController interface for managing ServiceAccount resources. type ServiceAccountController interface { generic.ControllerMeta ServiceAccountClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync ServiceAccountHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync ServiceAccountHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(namespace, name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() ServiceAccountCache } +// ServiceAccountClient interface for managing ServiceAccount resources in Kubernetes. type ServiceAccountClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.ServiceAccount) (*v1.ServiceAccount, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.ServiceAccount) (*v1.ServiceAccount, error) + // Delete deletes the Object in the given name. Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(namespace, name string, options metav1.GetOptions) (*v1.ServiceAccount, error) + + // List will attempt to find multiple resources. List(namespace string, opts metav1.ListOptions) (*v1.ServiceAccountList, error) + + // Watch will start watching resources. Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.ServiceAccount, err error) } +// ServiceAccountCache interface for retrieving ServiceAccount resources in memory. type ServiceAccountCache interface { + // Get returns the resources with the specified name from the cache. Get(namespace, name string) (*v1.ServiceAccount, error) + + // List will attempt to find resources from the Cache. List(namespace string, selector labels.Selector) ([]*v1.ServiceAccount, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer ServiceAccountIndexer) - GetByIndex(indexName, key string) ([]*v1.ServiceAccount, error) -} - -type ServiceAccountIndexer func(obj *v1.ServiceAccount) ([]string, error) - -type serviceAccountController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewServiceAccountController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) ServiceAccountController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &serviceAccountController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromServiceAccountHandlerToHandler(sync ServiceAccountHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.ServiceAccount - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.ServiceAccount)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *serviceAccountController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.ServiceAccount)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateServiceAccountDeepCopyOnChange(client ServiceAccountClient, obj *v1.ServiceAccount, handler func(obj *v1.ServiceAccount) (*v1.ServiceAccount, error)) (*v1.ServiceAccount, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *serviceAccountController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} -func (c *serviceAccountController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *serviceAccountController) OnChange(ctx context.Context, name string, sync ServiceAccountHandler) { - c.AddGenericHandler(ctx, name, FromServiceAccountHandlerToHandler(sync)) -} - -func (c *serviceAccountController) OnRemove(ctx context.Context, name string, sync ServiceAccountHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromServiceAccountHandlerToHandler(sync))) -} - -func (c *serviceAccountController) Enqueue(namespace, name string) { - c.controller.Enqueue(namespace, name) -} - -func (c *serviceAccountController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controller.EnqueueAfter(namespace, name, duration) -} - -func (c *serviceAccountController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *serviceAccountController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *serviceAccountController) Cache() ServiceAccountCache { - return &serviceAccountCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *serviceAccountController) Create(obj *v1.ServiceAccount) (*v1.ServiceAccount, error) { - result := &v1.ServiceAccount{} - return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) -} - -func (c *serviceAccountController) Update(obj *v1.ServiceAccount) (*v1.ServiceAccount, error) { - result := &v1.ServiceAccount{} - return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} - -func (c *serviceAccountController) Delete(namespace, name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), namespace, name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.ServiceAccount, error) } -func (c *serviceAccountController) Get(namespace, name string, options metav1.GetOptions) (*v1.ServiceAccount, error) { - result := &v1.ServiceAccount{} - return result, c.client.Get(context.TODO(), namespace, name, result, options) -} +// ServiceAccountHandler is function for performing any potential modifications to a ServiceAccount resource. +type ServiceAccountHandler func(string, *v1.ServiceAccount) (*v1.ServiceAccount, error) -func (c *serviceAccountController) List(namespace string, opts metav1.ListOptions) (*v1.ServiceAccountList, error) { - result := &v1.ServiceAccountList{} - return result, c.client.List(context.TODO(), namespace, result, opts) -} +// ServiceAccountIndexer computes a set of indexed values for the provided object. +type ServiceAccountIndexer func(obj *v1.ServiceAccount) ([]string, error) -func (c *serviceAccountController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), namespace, opts) +// ServiceAccountGenericController wraps wrangler/pkg/generic.Controller so that the function definitions adhere to ServiceAccountController interface. +type ServiceAccountGenericController struct { + generic.ControllerInterface[*v1.ServiceAccount, *v1.ServiceAccountList] } -func (c *serviceAccountController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.ServiceAccount, error) { - result := &v1.ServiceAccount{} - return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *ServiceAccountGenericController) OnChange(ctx context.Context, name string, sync ServiceAccountHandler) { + c.ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.ServiceAccount](sync)) } -type serviceAccountCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *ServiceAccountGenericController) OnRemove(ctx context.Context, name string, sync ServiceAccountHandler) { + c.ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.ServiceAccount](sync)) } -func (c *serviceAccountCache) Get(namespace, name string) (*v1.ServiceAccount, error) { - obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *ServiceAccountGenericController) Cache() ServiceAccountCache { + return &ServiceAccountGenericCache{ + c.ControllerInterface.Cache(), } - return obj.(*v1.ServiceAccount), nil -} - -func (c *serviceAccountCache) List(namespace string, selector labels.Selector) (ret []*v1.ServiceAccount, err error) { - - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.ServiceAccount)) - }) - - return ret, err } -func (c *serviceAccountCache) AddIndexer(indexName string, indexer ServiceAccountIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.ServiceAccount)) - }, - })) +// ServiceAccountGenericCache wraps wrangler/pkg/generic.Cache so the function definitions adhere to ServiceAccountCache interface. +type ServiceAccountGenericCache struct { + generic.CacheInterface[*v1.ServiceAccount] } -func (c *serviceAccountCache) GetByIndex(indexName, key string) (result []*v1.ServiceAccount, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.ServiceAccount, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.ServiceAccount)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c ServiceAccountGenericCache) AddIndexer(indexName string, indexer ServiceAccountIndexer) { + c.CacheInterface.AddIndexer(indexName, generic.Indexer[*v1.ServiceAccount](indexer)) } diff --git a/pkg/generated/controllers/discovery/v1/endpointslice.go b/pkg/generated/controllers/discovery/v1/endpointslice.go index 93d9e197..5e326475 100644 --- a/pkg/generated/controllers/discovery/v1/endpointslice.go +++ b/pkg/generated/controllers/discovery/v1/endpointslice.go @@ -22,235 +22,111 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/discovery/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type EndpointSliceHandler func(string, *v1.EndpointSlice) (*v1.EndpointSlice, error) - +// EndpointSliceController interface for managing EndpointSlice resources. type EndpointSliceController interface { generic.ControllerMeta EndpointSliceClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync EndpointSliceHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync EndpointSliceHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(namespace, name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() EndpointSliceCache } +// EndpointSliceClient interface for managing EndpointSlice resources in Kubernetes. type EndpointSliceClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.EndpointSlice) (*v1.EndpointSlice, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.EndpointSlice) (*v1.EndpointSlice, error) + // Delete deletes the Object in the given name. Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(namespace, name string, options metav1.GetOptions) (*v1.EndpointSlice, error) + + // List will attempt to find multiple resources. List(namespace string, opts metav1.ListOptions) (*v1.EndpointSliceList, error) + + // Watch will start watching resources. Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.EndpointSlice, err error) } +// EndpointSliceCache interface for retrieving EndpointSlice resources in memory. type EndpointSliceCache interface { + // Get returns the resources with the specified name from the cache. Get(namespace, name string) (*v1.EndpointSlice, error) + + // List will attempt to find resources from the Cache. List(namespace string, selector labels.Selector) ([]*v1.EndpointSlice, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer EndpointSliceIndexer) - GetByIndex(indexName, key string) ([]*v1.EndpointSlice, error) -} - -type EndpointSliceIndexer func(obj *v1.EndpointSlice) ([]string, error) - -type endpointSliceController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewEndpointSliceController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) EndpointSliceController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &endpointSliceController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromEndpointSliceHandlerToHandler(sync EndpointSliceHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.EndpointSlice - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.EndpointSlice)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *endpointSliceController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.EndpointSlice)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateEndpointSliceDeepCopyOnChange(client EndpointSliceClient, obj *v1.EndpointSlice, handler func(obj *v1.EndpointSlice) (*v1.EndpointSlice, error)) (*v1.EndpointSlice, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *endpointSliceController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} -func (c *endpointSliceController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *endpointSliceController) OnChange(ctx context.Context, name string, sync EndpointSliceHandler) { - c.AddGenericHandler(ctx, name, FromEndpointSliceHandlerToHandler(sync)) -} - -func (c *endpointSliceController) OnRemove(ctx context.Context, name string, sync EndpointSliceHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromEndpointSliceHandlerToHandler(sync))) -} - -func (c *endpointSliceController) Enqueue(namespace, name string) { - c.controller.Enqueue(namespace, name) -} - -func (c *endpointSliceController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controller.EnqueueAfter(namespace, name, duration) -} - -func (c *endpointSliceController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *endpointSliceController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *endpointSliceController) Cache() EndpointSliceCache { - return &endpointSliceCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *endpointSliceController) Create(obj *v1.EndpointSlice) (*v1.EndpointSlice, error) { - result := &v1.EndpointSlice{} - return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) -} - -func (c *endpointSliceController) Update(obj *v1.EndpointSlice) (*v1.EndpointSlice, error) { - result := &v1.EndpointSlice{} - return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} - -func (c *endpointSliceController) Delete(namespace, name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), namespace, name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.EndpointSlice, error) } -func (c *endpointSliceController) Get(namespace, name string, options metav1.GetOptions) (*v1.EndpointSlice, error) { - result := &v1.EndpointSlice{} - return result, c.client.Get(context.TODO(), namespace, name, result, options) -} +// EndpointSliceHandler is function for performing any potential modifications to a EndpointSlice resource. +type EndpointSliceHandler func(string, *v1.EndpointSlice) (*v1.EndpointSlice, error) -func (c *endpointSliceController) List(namespace string, opts metav1.ListOptions) (*v1.EndpointSliceList, error) { - result := &v1.EndpointSliceList{} - return result, c.client.List(context.TODO(), namespace, result, opts) -} +// EndpointSliceIndexer computes a set of indexed values for the provided object. +type EndpointSliceIndexer func(obj *v1.EndpointSlice) ([]string, error) -func (c *endpointSliceController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), namespace, opts) +// EndpointSliceGenericController wraps wrangler/pkg/generic.Controller so that the function definitions adhere to EndpointSliceController interface. +type EndpointSliceGenericController struct { + generic.ControllerInterface[*v1.EndpointSlice, *v1.EndpointSliceList] } -func (c *endpointSliceController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.EndpointSlice, error) { - result := &v1.EndpointSlice{} - return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *EndpointSliceGenericController) OnChange(ctx context.Context, name string, sync EndpointSliceHandler) { + c.ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.EndpointSlice](sync)) } -type endpointSliceCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *EndpointSliceGenericController) OnRemove(ctx context.Context, name string, sync EndpointSliceHandler) { + c.ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.EndpointSlice](sync)) } -func (c *endpointSliceCache) Get(namespace, name string) (*v1.EndpointSlice, error) { - obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *EndpointSliceGenericController) Cache() EndpointSliceCache { + return &EndpointSliceGenericCache{ + c.ControllerInterface.Cache(), } - return obj.(*v1.EndpointSlice), nil -} - -func (c *endpointSliceCache) List(namespace string, selector labels.Selector) (ret []*v1.EndpointSlice, err error) { - - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.EndpointSlice)) - }) - - return ret, err } -func (c *endpointSliceCache) AddIndexer(indexName string, indexer EndpointSliceIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.EndpointSlice)) - }, - })) +// EndpointSliceGenericCache wraps wrangler/pkg/generic.Cache so the function definitions adhere to EndpointSliceCache interface. +type EndpointSliceGenericCache struct { + generic.CacheInterface[*v1.EndpointSlice] } -func (c *endpointSliceCache) GetByIndex(indexName, key string) (result []*v1.EndpointSlice, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.EndpointSlice, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.EndpointSlice)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c EndpointSliceGenericCache) AddIndexer(indexName string, indexer EndpointSliceIndexer) { + c.CacheInterface.AddIndexer(indexName, generic.Indexer[*v1.EndpointSlice](indexer)) } diff --git a/pkg/generated/controllers/discovery/v1/interface.go b/pkg/generated/controllers/discovery/v1/interface.go index ef5d30d4..4c0118e9 100644 --- a/pkg/generated/controllers/discovery/v1/interface.go +++ b/pkg/generated/controllers/discovery/v1/interface.go @@ -20,6 +20,7 @@ package v1 import ( "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/generic" "github.com/rancher/wrangler/pkg/schemes" v1 "k8s.io/api/discovery/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -43,6 +44,8 @@ type version struct { controllerFactory controller.SharedControllerFactory } -func (c *version) EndpointSlice() EndpointSliceController { - return NewEndpointSliceController(schema.GroupVersionKind{Group: "discovery.k8s.io", Version: "v1", Kind: "EndpointSlice"}, "endpointslices", true, c.controllerFactory) +func (v *version) EndpointSlice() EndpointSliceController { + return &EndpointSliceGenericController{ + generic.NewController[*v1.EndpointSlice, *v1.EndpointSliceList](schema.GroupVersionKind{Group: "discovery.k8s.io", Version: "v1", Kind: "EndpointSlice"}, "endpointslices", true, v.controllerFactory), + } } diff --git a/pkg/generated/controllers/extensions/v1beta1/ingress.go b/pkg/generated/controllers/extensions/v1beta1/ingress.go index 5bdbaf47..c2e37f14 100644 --- a/pkg/generated/controllers/extensions/v1beta1/ingress.go +++ b/pkg/generated/controllers/extensions/v1beta1/ingress.go @@ -22,8 +22,6 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,237 +34,121 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type IngressHandler func(string, *v1beta1.Ingress) (*v1beta1.Ingress, error) - +// IngressController interface for managing Ingress resources. type IngressController interface { generic.ControllerMeta IngressClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync IngressHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync IngressHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(namespace, name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() IngressCache } +// IngressClient interface for managing Ingress resources in Kubernetes. type IngressClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1beta1.Ingress) (*v1beta1.Ingress, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1beta1.Ingress) (*v1beta1.Ingress, error) + // UpdateStatus updates the Status field of a the object and return the newly updated Object or an error. + // Will always return an error if the object does not have a status field. UpdateStatus(*v1beta1.Ingress) (*v1beta1.Ingress, error) + + // Delete deletes the Object in the given name. Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(namespace, name string, options metav1.GetOptions) (*v1beta1.Ingress, error) + + // List will attempt to find multiple resources. List(namespace string, opts metav1.ListOptions) (*v1beta1.IngressList, error) + + // Watch will start watching resources. Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.Ingress, err error) } +// IngressCache interface for retrieving Ingress resources in memory. type IngressCache interface { + // Get returns the resources with the specified name from the cache. Get(namespace, name string) (*v1beta1.Ingress, error) + + // List will attempt to find resources from the Cache. List(namespace string, selector labels.Selector) ([]*v1beta1.Ingress, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer IngressIndexer) - GetByIndex(indexName, key string) ([]*v1beta1.Ingress, error) -} - -type IngressIndexer func(obj *v1beta1.Ingress) ([]string, error) - -type ingressController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewIngressController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) IngressController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &ingressController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromIngressHandlerToHandler(sync IngressHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1beta1.Ingress - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1beta1.Ingress)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *ingressController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1beta1.Ingress)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateIngressDeepCopyOnChange(client IngressClient, obj *v1beta1.Ingress, handler func(obj *v1beta1.Ingress) (*v1beta1.Ingress, error)) (*v1beta1.Ingress, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *ingressController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} - -func (c *ingressController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *ingressController) OnChange(ctx context.Context, name string, sync IngressHandler) { - c.AddGenericHandler(ctx, name, FromIngressHandlerToHandler(sync)) -} - -func (c *ingressController) OnRemove(ctx context.Context, name string, sync IngressHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromIngressHandlerToHandler(sync))) -} - -func (c *ingressController) Enqueue(namespace, name string) { - c.controller.Enqueue(namespace, name) -} - -func (c *ingressController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controller.EnqueueAfter(namespace, name, duration) -} - -func (c *ingressController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *ingressController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *ingressController) Cache() IngressCache { - return &ingressCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *ingressController) Create(obj *v1beta1.Ingress) (*v1beta1.Ingress, error) { - result := &v1beta1.Ingress{} - return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) -} - -func (c *ingressController) Update(obj *v1beta1.Ingress) (*v1beta1.Ingress, error) { - result := &v1beta1.Ingress{} - return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} - -func (c *ingressController) UpdateStatus(obj *v1beta1.Ingress) (*v1beta1.Ingress, error) { - result := &v1beta1.Ingress{} - return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} -func (c *ingressController) Delete(namespace, name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), namespace, name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1beta1.Ingress, error) } -func (c *ingressController) Get(namespace, name string, options metav1.GetOptions) (*v1beta1.Ingress, error) { - result := &v1beta1.Ingress{} - return result, c.client.Get(context.TODO(), namespace, name, result, options) -} +// IngressHandler is function for performing any potential modifications to a Ingress resource. +type IngressHandler func(string, *v1beta1.Ingress) (*v1beta1.Ingress, error) -func (c *ingressController) List(namespace string, opts metav1.ListOptions) (*v1beta1.IngressList, error) { - result := &v1beta1.IngressList{} - return result, c.client.List(context.TODO(), namespace, result, opts) -} +// IngressIndexer computes a set of indexed values for the provided object. +type IngressIndexer func(obj *v1beta1.Ingress) ([]string, error) -func (c *ingressController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), namespace, opts) +// IngressGenericController wraps wrangler/pkg/generic.Controller so that the function definitions adhere to IngressController interface. +type IngressGenericController struct { + generic.ControllerInterface[*v1beta1.Ingress, *v1beta1.IngressList] } -func (c *ingressController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1beta1.Ingress, error) { - result := &v1beta1.Ingress{} - return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *IngressGenericController) OnChange(ctx context.Context, name string, sync IngressHandler) { + c.ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1beta1.Ingress](sync)) } -type ingressCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *IngressGenericController) OnRemove(ctx context.Context, name string, sync IngressHandler) { + c.ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1beta1.Ingress](sync)) } -func (c *ingressCache) Get(namespace, name string) (*v1beta1.Ingress, error) { - obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *IngressGenericController) Cache() IngressCache { + return &IngressGenericCache{ + c.ControllerInterface.Cache(), } - return obj.(*v1beta1.Ingress), nil } -func (c *ingressCache) List(namespace string, selector labels.Selector) (ret []*v1beta1.Ingress, err error) { - - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1beta1.Ingress)) - }) - - return ret, err +// IngressGenericCache wraps wrangler/pkg/generic.Cache so the function definitions adhere to IngressCache interface. +type IngressGenericCache struct { + generic.CacheInterface[*v1beta1.Ingress] } -func (c *ingressCache) AddIndexer(indexName string, indexer IngressIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1beta1.Ingress)) - }, - })) -} - -func (c *ingressCache) GetByIndex(indexName, key string) (result []*v1beta1.Ingress, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1beta1.Ingress, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1beta1.Ingress)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c IngressGenericCache) AddIndexer(indexName string, indexer IngressIndexer) { + c.CacheInterface.AddIndexer(indexName, generic.Indexer[*v1beta1.Ingress](indexer)) } type IngressStatusHandler func(obj *v1beta1.Ingress, status v1beta1.IngressStatus) (v1beta1.IngressStatus, error) type IngressGeneratingHandler func(obj *v1beta1.Ingress, status v1beta1.IngressStatus) ([]runtime.Object, v1beta1.IngressStatus, error) +func FromIngressHandlerToHandler(sync IngressHandler) generic.Handler { + return generic.FromObjectHandlerToHandler(generic.ObjectHandler[*v1beta1.Ingress](sync)) +} + func RegisterIngressStatusHandler(ctx context.Context, controller IngressController, condition condition.Cond, name string, handler IngressStatusHandler) { statusHandler := &ingressStatusHandler{ client: controller, diff --git a/pkg/generated/controllers/extensions/v1beta1/interface.go b/pkg/generated/controllers/extensions/v1beta1/interface.go index f49042fa..4ec8500b 100644 --- a/pkg/generated/controllers/extensions/v1beta1/interface.go +++ b/pkg/generated/controllers/extensions/v1beta1/interface.go @@ -20,6 +20,7 @@ package v1beta1 import ( "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/generic" "github.com/rancher/wrangler/pkg/schemes" v1beta1 "k8s.io/api/extensions/v1beta1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -43,6 +44,8 @@ type version struct { controllerFactory controller.SharedControllerFactory } -func (c *version) Ingress() IngressController { - return NewIngressController(schema.GroupVersionKind{Group: "extensions", Version: "v1beta1", Kind: "Ingress"}, "ingresses", true, c.controllerFactory) +func (v *version) Ingress() IngressController { + return &IngressGenericController{ + generic.NewController[*v1beta1.Ingress, *v1beta1.IngressList](schema.GroupVersionKind{Group: "extensions", Version: "v1beta1", Kind: "Ingress"}, "ingresses", true, v.controllerFactory), + } } diff --git a/pkg/generated/controllers/networking.k8s.io/v1/interface.go b/pkg/generated/controllers/networking.k8s.io/v1/interface.go index cb9ac509..2afdab37 100644 --- a/pkg/generated/controllers/networking.k8s.io/v1/interface.go +++ b/pkg/generated/controllers/networking.k8s.io/v1/interface.go @@ -20,6 +20,7 @@ package v1 import ( "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/generic" "github.com/rancher/wrangler/pkg/schemes" v1 "k8s.io/api/networking/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -43,6 +44,8 @@ type version struct { controllerFactory controller.SharedControllerFactory } -func (c *version) NetworkPolicy() NetworkPolicyController { - return NewNetworkPolicyController(schema.GroupVersionKind{Group: "networking.k8s.io", Version: "v1", Kind: "NetworkPolicy"}, "networkpolicies", true, c.controllerFactory) +func (v *version) NetworkPolicy() NetworkPolicyController { + return &NetworkPolicyGenericController{ + generic.NewController[*v1.NetworkPolicy, *v1.NetworkPolicyList](schema.GroupVersionKind{Group: "networking.k8s.io", Version: "v1", Kind: "NetworkPolicy"}, "networkpolicies", true, v.controllerFactory), + } } diff --git a/pkg/generated/controllers/networking.k8s.io/v1/networkpolicy.go b/pkg/generated/controllers/networking.k8s.io/v1/networkpolicy.go index e95dc004..be284508 100644 --- a/pkg/generated/controllers/networking.k8s.io/v1/networkpolicy.go +++ b/pkg/generated/controllers/networking.k8s.io/v1/networkpolicy.go @@ -22,8 +22,6 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/apply" "github.com/rancher/wrangler/pkg/condition" "github.com/rancher/wrangler/pkg/generic" @@ -36,237 +34,121 @@ import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type NetworkPolicyHandler func(string, *v1.NetworkPolicy) (*v1.NetworkPolicy, error) - +// NetworkPolicyController interface for managing NetworkPolicy resources. type NetworkPolicyController interface { generic.ControllerMeta NetworkPolicyClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync NetworkPolicyHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync NetworkPolicyHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(namespace, name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() NetworkPolicyCache } +// NetworkPolicyClient interface for managing NetworkPolicy resources in Kubernetes. type NetworkPolicyClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.NetworkPolicy) (*v1.NetworkPolicy, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.NetworkPolicy) (*v1.NetworkPolicy, error) + // UpdateStatus updates the Status field of a the object and return the newly updated Object or an error. + // Will always return an error if the object does not have a status field. UpdateStatus(*v1.NetworkPolicy) (*v1.NetworkPolicy, error) + + // Delete deletes the Object in the given name. Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(namespace, name string, options metav1.GetOptions) (*v1.NetworkPolicy, error) + + // List will attempt to find multiple resources. List(namespace string, opts metav1.ListOptions) (*v1.NetworkPolicyList, error) + + // Watch will start watching resources. Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.NetworkPolicy, err error) } +// NetworkPolicyCache interface for retrieving NetworkPolicy resources in memory. type NetworkPolicyCache interface { + // Get returns the resources with the specified name from the cache. Get(namespace, name string) (*v1.NetworkPolicy, error) + + // List will attempt to find resources from the Cache. List(namespace string, selector labels.Selector) ([]*v1.NetworkPolicy, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer NetworkPolicyIndexer) - GetByIndex(indexName, key string) ([]*v1.NetworkPolicy, error) -} - -type NetworkPolicyIndexer func(obj *v1.NetworkPolicy) ([]string, error) - -type networkPolicyController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewNetworkPolicyController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) NetworkPolicyController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &networkPolicyController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromNetworkPolicyHandlerToHandler(sync NetworkPolicyHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.NetworkPolicy - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.NetworkPolicy)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *networkPolicyController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.NetworkPolicy)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateNetworkPolicyDeepCopyOnChange(client NetworkPolicyClient, obj *v1.NetworkPolicy, handler func(obj *v1.NetworkPolicy) (*v1.NetworkPolicy, error)) (*v1.NetworkPolicy, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *networkPolicyController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} - -func (c *networkPolicyController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *networkPolicyController) OnChange(ctx context.Context, name string, sync NetworkPolicyHandler) { - c.AddGenericHandler(ctx, name, FromNetworkPolicyHandlerToHandler(sync)) -} - -func (c *networkPolicyController) OnRemove(ctx context.Context, name string, sync NetworkPolicyHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromNetworkPolicyHandlerToHandler(sync))) -} - -func (c *networkPolicyController) Enqueue(namespace, name string) { - c.controller.Enqueue(namespace, name) -} - -func (c *networkPolicyController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controller.EnqueueAfter(namespace, name, duration) -} - -func (c *networkPolicyController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *networkPolicyController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *networkPolicyController) Cache() NetworkPolicyCache { - return &networkPolicyCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *networkPolicyController) Create(obj *v1.NetworkPolicy) (*v1.NetworkPolicy, error) { - result := &v1.NetworkPolicy{} - return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) -} - -func (c *networkPolicyController) Update(obj *v1.NetworkPolicy) (*v1.NetworkPolicy, error) { - result := &v1.NetworkPolicy{} - return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} - -func (c *networkPolicyController) UpdateStatus(obj *v1.NetworkPolicy) (*v1.NetworkPolicy, error) { - result := &v1.NetworkPolicy{} - return result, c.client.UpdateStatus(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} -func (c *networkPolicyController) Delete(namespace, name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), namespace, name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.NetworkPolicy, error) } -func (c *networkPolicyController) Get(namespace, name string, options metav1.GetOptions) (*v1.NetworkPolicy, error) { - result := &v1.NetworkPolicy{} - return result, c.client.Get(context.TODO(), namespace, name, result, options) -} +// NetworkPolicyHandler is function for performing any potential modifications to a NetworkPolicy resource. +type NetworkPolicyHandler func(string, *v1.NetworkPolicy) (*v1.NetworkPolicy, error) -func (c *networkPolicyController) List(namespace string, opts metav1.ListOptions) (*v1.NetworkPolicyList, error) { - result := &v1.NetworkPolicyList{} - return result, c.client.List(context.TODO(), namespace, result, opts) -} +// NetworkPolicyIndexer computes a set of indexed values for the provided object. +type NetworkPolicyIndexer func(obj *v1.NetworkPolicy) ([]string, error) -func (c *networkPolicyController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), namespace, opts) +// NetworkPolicyGenericController wraps wrangler/pkg/generic.Controller so that the function definitions adhere to NetworkPolicyController interface. +type NetworkPolicyGenericController struct { + generic.ControllerInterface[*v1.NetworkPolicy, *v1.NetworkPolicyList] } -func (c *networkPolicyController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.NetworkPolicy, error) { - result := &v1.NetworkPolicy{} - return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *NetworkPolicyGenericController) OnChange(ctx context.Context, name string, sync NetworkPolicyHandler) { + c.ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.NetworkPolicy](sync)) } -type networkPolicyCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *NetworkPolicyGenericController) OnRemove(ctx context.Context, name string, sync NetworkPolicyHandler) { + c.ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.NetworkPolicy](sync)) } -func (c *networkPolicyCache) Get(namespace, name string) (*v1.NetworkPolicy, error) { - obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *NetworkPolicyGenericController) Cache() NetworkPolicyCache { + return &NetworkPolicyGenericCache{ + c.ControllerInterface.Cache(), } - return obj.(*v1.NetworkPolicy), nil } -func (c *networkPolicyCache) List(namespace string, selector labels.Selector) (ret []*v1.NetworkPolicy, err error) { - - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.NetworkPolicy)) - }) - - return ret, err +// NetworkPolicyGenericCache wraps wrangler/pkg/generic.Cache so the function definitions adhere to NetworkPolicyCache interface. +type NetworkPolicyGenericCache struct { + generic.CacheInterface[*v1.NetworkPolicy] } -func (c *networkPolicyCache) AddIndexer(indexName string, indexer NetworkPolicyIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.NetworkPolicy)) - }, - })) -} - -func (c *networkPolicyCache) GetByIndex(indexName, key string) (result []*v1.NetworkPolicy, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.NetworkPolicy, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.NetworkPolicy)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c NetworkPolicyGenericCache) AddIndexer(indexName string, indexer NetworkPolicyIndexer) { + c.CacheInterface.AddIndexer(indexName, generic.Indexer[*v1.NetworkPolicy](indexer)) } type NetworkPolicyStatusHandler func(obj *v1.NetworkPolicy, status v1.NetworkPolicyStatus) (v1.NetworkPolicyStatus, error) type NetworkPolicyGeneratingHandler func(obj *v1.NetworkPolicy, status v1.NetworkPolicyStatus) ([]runtime.Object, v1.NetworkPolicyStatus, error) +func FromNetworkPolicyHandlerToHandler(sync NetworkPolicyHandler) generic.Handler { + return generic.FromObjectHandlerToHandler(generic.ObjectHandler[*v1.NetworkPolicy](sync)) +} + func RegisterNetworkPolicyStatusHandler(ctx context.Context, controller NetworkPolicyController, condition condition.Cond, name string, handler NetworkPolicyStatusHandler) { statusHandler := &networkPolicyStatusHandler{ client: controller, diff --git a/pkg/generated/controllers/rbac/v1/clusterrole.go b/pkg/generated/controllers/rbac/v1/clusterrole.go index 1c192736..ae4a0f39 100644 --- a/pkg/generated/controllers/rbac/v1/clusterrole.go +++ b/pkg/generated/controllers/rbac/v1/clusterrole.go @@ -22,235 +22,111 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/rbac/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type ClusterRoleHandler func(string, *v1.ClusterRole) (*v1.ClusterRole, error) - +// ClusterRoleController interface for managing ClusterRole resources. type ClusterRoleController interface { generic.ControllerMeta ClusterRoleClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync ClusterRoleHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync ClusterRoleHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() ClusterRoleCache } +// ClusterRoleClient interface for managing ClusterRole resources in Kubernetes. type ClusterRoleClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.ClusterRole) (*v1.ClusterRole, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.ClusterRole) (*v1.ClusterRole, error) + // Delete deletes the Object in the given name. Delete(name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(name string, options metav1.GetOptions) (*v1.ClusterRole, error) + + // List will attempt to find multiple resources. List(opts metav1.ListOptions) (*v1.ClusterRoleList, error) + + // Watch will start watching resources. Watch(opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.ClusterRole, err error) } +// ClusterRoleCache interface for retrieving ClusterRole resources in memory. type ClusterRoleCache interface { + // Get returns the resources with the specified name from the cache. Get(name string) (*v1.ClusterRole, error) + + // List will attempt to find resources from the Cache. List(selector labels.Selector) ([]*v1.ClusterRole, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer ClusterRoleIndexer) - GetByIndex(indexName, key string) ([]*v1.ClusterRole, error) -} - -type ClusterRoleIndexer func(obj *v1.ClusterRole) ([]string, error) - -type clusterRoleController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewClusterRoleController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) ClusterRoleController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &clusterRoleController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromClusterRoleHandlerToHandler(sync ClusterRoleHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.ClusterRole - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.ClusterRole)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *clusterRoleController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.ClusterRole)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateClusterRoleDeepCopyOnChange(client ClusterRoleClient, obj *v1.ClusterRole, handler func(obj *v1.ClusterRole) (*v1.ClusterRole, error)) (*v1.ClusterRole, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *clusterRoleController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} -func (c *clusterRoleController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *clusterRoleController) OnChange(ctx context.Context, name string, sync ClusterRoleHandler) { - c.AddGenericHandler(ctx, name, FromClusterRoleHandlerToHandler(sync)) -} - -func (c *clusterRoleController) OnRemove(ctx context.Context, name string, sync ClusterRoleHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromClusterRoleHandlerToHandler(sync))) -} - -func (c *clusterRoleController) Enqueue(name string) { - c.controller.Enqueue("", name) -} - -func (c *clusterRoleController) EnqueueAfter(name string, duration time.Duration) { - c.controller.EnqueueAfter("", name, duration) -} - -func (c *clusterRoleController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *clusterRoleController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *clusterRoleController) Cache() ClusterRoleCache { - return &clusterRoleCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *clusterRoleController) Create(obj *v1.ClusterRole) (*v1.ClusterRole, error) { - result := &v1.ClusterRole{} - return result, c.client.Create(context.TODO(), "", obj, result, metav1.CreateOptions{}) -} - -func (c *clusterRoleController) Update(obj *v1.ClusterRole) (*v1.ClusterRole, error) { - result := &v1.ClusterRole{} - return result, c.client.Update(context.TODO(), "", obj, result, metav1.UpdateOptions{}) -} - -func (c *clusterRoleController) Delete(name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), "", name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.ClusterRole, error) } -func (c *clusterRoleController) Get(name string, options metav1.GetOptions) (*v1.ClusterRole, error) { - result := &v1.ClusterRole{} - return result, c.client.Get(context.TODO(), "", name, result, options) -} +// ClusterRoleHandler is function for performing any potential modifications to a ClusterRole resource. +type ClusterRoleHandler func(string, *v1.ClusterRole) (*v1.ClusterRole, error) -func (c *clusterRoleController) List(opts metav1.ListOptions) (*v1.ClusterRoleList, error) { - result := &v1.ClusterRoleList{} - return result, c.client.List(context.TODO(), "", result, opts) -} +// ClusterRoleIndexer computes a set of indexed values for the provided object. +type ClusterRoleIndexer func(obj *v1.ClusterRole) ([]string, error) -func (c *clusterRoleController) Watch(opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), "", opts) +// ClusterRoleGenericController wraps wrangler/pkg/generic.NonNamespacedController so that the function definitions adhere to ClusterRoleController interface. +type ClusterRoleGenericController struct { + generic.NonNamespacedControllerInterface[*v1.ClusterRole, *v1.ClusterRoleList] } -func (c *clusterRoleController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v1.ClusterRole, error) { - result := &v1.ClusterRole{} - return result, c.client.Patch(context.TODO(), "", name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *ClusterRoleGenericController) OnChange(ctx context.Context, name string, sync ClusterRoleHandler) { + c.NonNamespacedControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.ClusterRole](sync)) } -type clusterRoleCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *ClusterRoleGenericController) OnRemove(ctx context.Context, name string, sync ClusterRoleHandler) { + c.NonNamespacedControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.ClusterRole](sync)) } -func (c *clusterRoleCache) Get(name string) (*v1.ClusterRole, error) { - obj, exists, err := c.indexer.GetByKey(name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *ClusterRoleGenericController) Cache() ClusterRoleCache { + return &ClusterRoleGenericCache{ + c.NonNamespacedControllerInterface.Cache(), } - return obj.(*v1.ClusterRole), nil -} - -func (c *clusterRoleCache) List(selector labels.Selector) (ret []*v1.ClusterRole, err error) { - - err = cache.ListAll(c.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1.ClusterRole)) - }) - - return ret, err } -func (c *clusterRoleCache) AddIndexer(indexName string, indexer ClusterRoleIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.ClusterRole)) - }, - })) +// ClusterRoleGenericCache wraps wrangler/pkg/generic.NonNamespacedCache so the function definitions adhere to ClusterRoleCache interface. +type ClusterRoleGenericCache struct { + generic.NonNamespacedCacheInterface[*v1.ClusterRole] } -func (c *clusterRoleCache) GetByIndex(indexName, key string) (result []*v1.ClusterRole, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.ClusterRole, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.ClusterRole)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c ClusterRoleGenericCache) AddIndexer(indexName string, indexer ClusterRoleIndexer) { + c.NonNamespacedCacheInterface.AddIndexer(indexName, generic.Indexer[*v1.ClusterRole](indexer)) } diff --git a/pkg/generated/controllers/rbac/v1/clusterrolebinding.go b/pkg/generated/controllers/rbac/v1/clusterrolebinding.go index 8673b6a2..d1f13469 100644 --- a/pkg/generated/controllers/rbac/v1/clusterrolebinding.go +++ b/pkg/generated/controllers/rbac/v1/clusterrolebinding.go @@ -22,235 +22,111 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/rbac/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type ClusterRoleBindingHandler func(string, *v1.ClusterRoleBinding) (*v1.ClusterRoleBinding, error) - +// ClusterRoleBindingController interface for managing ClusterRoleBinding resources. type ClusterRoleBindingController interface { generic.ControllerMeta ClusterRoleBindingClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync ClusterRoleBindingHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync ClusterRoleBindingHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() ClusterRoleBindingCache } +// ClusterRoleBindingClient interface for managing ClusterRoleBinding resources in Kubernetes. type ClusterRoleBindingClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.ClusterRoleBinding) (*v1.ClusterRoleBinding, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.ClusterRoleBinding) (*v1.ClusterRoleBinding, error) + // Delete deletes the Object in the given name. Delete(name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(name string, options metav1.GetOptions) (*v1.ClusterRoleBinding, error) + + // List will attempt to find multiple resources. List(opts metav1.ListOptions) (*v1.ClusterRoleBindingList, error) + + // Watch will start watching resources. Watch(opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.ClusterRoleBinding, err error) } +// ClusterRoleBindingCache interface for retrieving ClusterRoleBinding resources in memory. type ClusterRoleBindingCache interface { + // Get returns the resources with the specified name from the cache. Get(name string) (*v1.ClusterRoleBinding, error) + + // List will attempt to find resources from the Cache. List(selector labels.Selector) ([]*v1.ClusterRoleBinding, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer ClusterRoleBindingIndexer) - GetByIndex(indexName, key string) ([]*v1.ClusterRoleBinding, error) -} - -type ClusterRoleBindingIndexer func(obj *v1.ClusterRoleBinding) ([]string, error) - -type clusterRoleBindingController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewClusterRoleBindingController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) ClusterRoleBindingController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &clusterRoleBindingController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromClusterRoleBindingHandlerToHandler(sync ClusterRoleBindingHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.ClusterRoleBinding - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.ClusterRoleBinding)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *clusterRoleBindingController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.ClusterRoleBinding)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateClusterRoleBindingDeepCopyOnChange(client ClusterRoleBindingClient, obj *v1.ClusterRoleBinding, handler func(obj *v1.ClusterRoleBinding) (*v1.ClusterRoleBinding, error)) (*v1.ClusterRoleBinding, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *clusterRoleBindingController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} -func (c *clusterRoleBindingController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *clusterRoleBindingController) OnChange(ctx context.Context, name string, sync ClusterRoleBindingHandler) { - c.AddGenericHandler(ctx, name, FromClusterRoleBindingHandlerToHandler(sync)) -} - -func (c *clusterRoleBindingController) OnRemove(ctx context.Context, name string, sync ClusterRoleBindingHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromClusterRoleBindingHandlerToHandler(sync))) -} - -func (c *clusterRoleBindingController) Enqueue(name string) { - c.controller.Enqueue("", name) -} - -func (c *clusterRoleBindingController) EnqueueAfter(name string, duration time.Duration) { - c.controller.EnqueueAfter("", name, duration) -} - -func (c *clusterRoleBindingController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *clusterRoleBindingController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *clusterRoleBindingController) Cache() ClusterRoleBindingCache { - return &clusterRoleBindingCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *clusterRoleBindingController) Create(obj *v1.ClusterRoleBinding) (*v1.ClusterRoleBinding, error) { - result := &v1.ClusterRoleBinding{} - return result, c.client.Create(context.TODO(), "", obj, result, metav1.CreateOptions{}) -} - -func (c *clusterRoleBindingController) Update(obj *v1.ClusterRoleBinding) (*v1.ClusterRoleBinding, error) { - result := &v1.ClusterRoleBinding{} - return result, c.client.Update(context.TODO(), "", obj, result, metav1.UpdateOptions{}) -} - -func (c *clusterRoleBindingController) Delete(name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), "", name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.ClusterRoleBinding, error) } -func (c *clusterRoleBindingController) Get(name string, options metav1.GetOptions) (*v1.ClusterRoleBinding, error) { - result := &v1.ClusterRoleBinding{} - return result, c.client.Get(context.TODO(), "", name, result, options) -} +// ClusterRoleBindingHandler is function for performing any potential modifications to a ClusterRoleBinding resource. +type ClusterRoleBindingHandler func(string, *v1.ClusterRoleBinding) (*v1.ClusterRoleBinding, error) -func (c *clusterRoleBindingController) List(opts metav1.ListOptions) (*v1.ClusterRoleBindingList, error) { - result := &v1.ClusterRoleBindingList{} - return result, c.client.List(context.TODO(), "", result, opts) -} +// ClusterRoleBindingIndexer computes a set of indexed values for the provided object. +type ClusterRoleBindingIndexer func(obj *v1.ClusterRoleBinding) ([]string, error) -func (c *clusterRoleBindingController) Watch(opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), "", opts) +// ClusterRoleBindingGenericController wraps wrangler/pkg/generic.NonNamespacedController so that the function definitions adhere to ClusterRoleBindingController interface. +type ClusterRoleBindingGenericController struct { + generic.NonNamespacedControllerInterface[*v1.ClusterRoleBinding, *v1.ClusterRoleBindingList] } -func (c *clusterRoleBindingController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v1.ClusterRoleBinding, error) { - result := &v1.ClusterRoleBinding{} - return result, c.client.Patch(context.TODO(), "", name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *ClusterRoleBindingGenericController) OnChange(ctx context.Context, name string, sync ClusterRoleBindingHandler) { + c.NonNamespacedControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.ClusterRoleBinding](sync)) } -type clusterRoleBindingCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *ClusterRoleBindingGenericController) OnRemove(ctx context.Context, name string, sync ClusterRoleBindingHandler) { + c.NonNamespacedControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.ClusterRoleBinding](sync)) } -func (c *clusterRoleBindingCache) Get(name string) (*v1.ClusterRoleBinding, error) { - obj, exists, err := c.indexer.GetByKey(name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *ClusterRoleBindingGenericController) Cache() ClusterRoleBindingCache { + return &ClusterRoleBindingGenericCache{ + c.NonNamespacedControllerInterface.Cache(), } - return obj.(*v1.ClusterRoleBinding), nil -} - -func (c *clusterRoleBindingCache) List(selector labels.Selector) (ret []*v1.ClusterRoleBinding, err error) { - - err = cache.ListAll(c.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1.ClusterRoleBinding)) - }) - - return ret, err } -func (c *clusterRoleBindingCache) AddIndexer(indexName string, indexer ClusterRoleBindingIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.ClusterRoleBinding)) - }, - })) +// ClusterRoleBindingGenericCache wraps wrangler/pkg/generic.NonNamespacedCache so the function definitions adhere to ClusterRoleBindingCache interface. +type ClusterRoleBindingGenericCache struct { + generic.NonNamespacedCacheInterface[*v1.ClusterRoleBinding] } -func (c *clusterRoleBindingCache) GetByIndex(indexName, key string) (result []*v1.ClusterRoleBinding, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.ClusterRoleBinding, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.ClusterRoleBinding)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c ClusterRoleBindingGenericCache) AddIndexer(indexName string, indexer ClusterRoleBindingIndexer) { + c.NonNamespacedCacheInterface.AddIndexer(indexName, generic.Indexer[*v1.ClusterRoleBinding](indexer)) } diff --git a/pkg/generated/controllers/rbac/v1/interface.go b/pkg/generated/controllers/rbac/v1/interface.go index 1dbb1045..63fa892e 100644 --- a/pkg/generated/controllers/rbac/v1/interface.go +++ b/pkg/generated/controllers/rbac/v1/interface.go @@ -20,6 +20,7 @@ package v1 import ( "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/generic" "github.com/rancher/wrangler/pkg/schemes" v1 "k8s.io/api/rbac/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -46,15 +47,26 @@ type version struct { controllerFactory controller.SharedControllerFactory } -func (c *version) ClusterRole() ClusterRoleController { - return NewClusterRoleController(schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "ClusterRole"}, "clusterroles", false, c.controllerFactory) +func (v *version) ClusterRole() ClusterRoleController { + return &ClusterRoleGenericController{ + generic.NewNonNamespacedController[*v1.ClusterRole, *v1.ClusterRoleList](schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "ClusterRole"}, "clusterroles", v.controllerFactory), + } } -func (c *version) ClusterRoleBinding() ClusterRoleBindingController { - return NewClusterRoleBindingController(schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "ClusterRoleBinding"}, "clusterrolebindings", false, c.controllerFactory) + +func (v *version) ClusterRoleBinding() ClusterRoleBindingController { + return &ClusterRoleBindingGenericController{ + generic.NewNonNamespacedController[*v1.ClusterRoleBinding, *v1.ClusterRoleBindingList](schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "ClusterRoleBinding"}, "clusterrolebindings", v.controllerFactory), + } } -func (c *version) Role() RoleController { - return NewRoleController(schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "Role"}, "roles", true, c.controllerFactory) + +func (v *version) Role() RoleController { + return &RoleGenericController{ + generic.NewController[*v1.Role, *v1.RoleList](schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "Role"}, "roles", true, v.controllerFactory), + } } -func (c *version) RoleBinding() RoleBindingController { - return NewRoleBindingController(schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "RoleBinding"}, "rolebindings", true, c.controllerFactory) + +func (v *version) RoleBinding() RoleBindingController { + return &RoleBindingGenericController{ + generic.NewController[*v1.RoleBinding, *v1.RoleBindingList](schema.GroupVersionKind{Group: "rbac.authorization.k8s.io", Version: "v1", Kind: "RoleBinding"}, "rolebindings", true, v.controllerFactory), + } } diff --git a/pkg/generated/controllers/rbac/v1/role.go b/pkg/generated/controllers/rbac/v1/role.go index a3b113ea..ef7d69df 100644 --- a/pkg/generated/controllers/rbac/v1/role.go +++ b/pkg/generated/controllers/rbac/v1/role.go @@ -22,235 +22,111 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/rbac/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type RoleHandler func(string, *v1.Role) (*v1.Role, error) - +// RoleController interface for managing Role resources. type RoleController interface { generic.ControllerMeta RoleClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync RoleHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync RoleHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(namespace, name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() RoleCache } +// RoleClient interface for managing Role resources in Kubernetes. type RoleClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.Role) (*v1.Role, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.Role) (*v1.Role, error) + // Delete deletes the Object in the given name. Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(namespace, name string, options metav1.GetOptions) (*v1.Role, error) + + // List will attempt to find multiple resources. List(namespace string, opts metav1.ListOptions) (*v1.RoleList, error) + + // Watch will start watching resources. Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.Role, err error) } +// RoleCache interface for retrieving Role resources in memory. type RoleCache interface { + // Get returns the resources with the specified name from the cache. Get(namespace, name string) (*v1.Role, error) + + // List will attempt to find resources from the Cache. List(namespace string, selector labels.Selector) ([]*v1.Role, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer RoleIndexer) - GetByIndex(indexName, key string) ([]*v1.Role, error) -} - -type RoleIndexer func(obj *v1.Role) ([]string, error) - -type roleController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewRoleController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) RoleController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &roleController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromRoleHandlerToHandler(sync RoleHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.Role - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.Role)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *roleController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.Role)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateRoleDeepCopyOnChange(client RoleClient, obj *v1.Role, handler func(obj *v1.Role) (*v1.Role, error)) (*v1.Role, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *roleController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} -func (c *roleController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *roleController) OnChange(ctx context.Context, name string, sync RoleHandler) { - c.AddGenericHandler(ctx, name, FromRoleHandlerToHandler(sync)) -} - -func (c *roleController) OnRemove(ctx context.Context, name string, sync RoleHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromRoleHandlerToHandler(sync))) -} - -func (c *roleController) Enqueue(namespace, name string) { - c.controller.Enqueue(namespace, name) -} - -func (c *roleController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controller.EnqueueAfter(namespace, name, duration) -} - -func (c *roleController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *roleController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *roleController) Cache() RoleCache { - return &roleCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *roleController) Create(obj *v1.Role) (*v1.Role, error) { - result := &v1.Role{} - return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) -} - -func (c *roleController) Update(obj *v1.Role) (*v1.Role, error) { - result := &v1.Role{} - return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} - -func (c *roleController) Delete(namespace, name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), namespace, name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.Role, error) } -func (c *roleController) Get(namespace, name string, options metav1.GetOptions) (*v1.Role, error) { - result := &v1.Role{} - return result, c.client.Get(context.TODO(), namespace, name, result, options) -} +// RoleHandler is function for performing any potential modifications to a Role resource. +type RoleHandler func(string, *v1.Role) (*v1.Role, error) -func (c *roleController) List(namespace string, opts metav1.ListOptions) (*v1.RoleList, error) { - result := &v1.RoleList{} - return result, c.client.List(context.TODO(), namespace, result, opts) -} +// RoleIndexer computes a set of indexed values for the provided object. +type RoleIndexer func(obj *v1.Role) ([]string, error) -func (c *roleController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), namespace, opts) +// RoleGenericController wraps wrangler/pkg/generic.Controller so that the function definitions adhere to RoleController interface. +type RoleGenericController struct { + generic.ControllerInterface[*v1.Role, *v1.RoleList] } -func (c *roleController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.Role, error) { - result := &v1.Role{} - return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *RoleGenericController) OnChange(ctx context.Context, name string, sync RoleHandler) { + c.ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.Role](sync)) } -type roleCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *RoleGenericController) OnRemove(ctx context.Context, name string, sync RoleHandler) { + c.ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.Role](sync)) } -func (c *roleCache) Get(namespace, name string) (*v1.Role, error) { - obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *RoleGenericController) Cache() RoleCache { + return &RoleGenericCache{ + c.ControllerInterface.Cache(), } - return obj.(*v1.Role), nil -} - -func (c *roleCache) List(namespace string, selector labels.Selector) (ret []*v1.Role, err error) { - - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.Role)) - }) - - return ret, err } -func (c *roleCache) AddIndexer(indexName string, indexer RoleIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.Role)) - }, - })) +// RoleGenericCache wraps wrangler/pkg/generic.Cache so the function definitions adhere to RoleCache interface. +type RoleGenericCache struct { + generic.CacheInterface[*v1.Role] } -func (c *roleCache) GetByIndex(indexName, key string) (result []*v1.Role, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.Role, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.Role)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c RoleGenericCache) AddIndexer(indexName string, indexer RoleIndexer) { + c.CacheInterface.AddIndexer(indexName, generic.Indexer[*v1.Role](indexer)) } diff --git a/pkg/generated/controllers/rbac/v1/rolebinding.go b/pkg/generated/controllers/rbac/v1/rolebinding.go index 383ffa15..d0f97079 100644 --- a/pkg/generated/controllers/rbac/v1/rolebinding.go +++ b/pkg/generated/controllers/rbac/v1/rolebinding.go @@ -22,235 +22,111 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/rbac/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type RoleBindingHandler func(string, *v1.RoleBinding) (*v1.RoleBinding, error) - +// RoleBindingController interface for managing RoleBinding resources. type RoleBindingController interface { generic.ControllerMeta RoleBindingClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync RoleBindingHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync RoleBindingHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(namespace, name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() RoleBindingCache } +// RoleBindingClient interface for managing RoleBinding resources in Kubernetes. type RoleBindingClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.RoleBinding) (*v1.RoleBinding, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.RoleBinding) (*v1.RoleBinding, error) + // Delete deletes the Object in the given name. Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(namespace, name string, options metav1.GetOptions) (*v1.RoleBinding, error) + + // List will attempt to find multiple resources. List(namespace string, opts metav1.ListOptions) (*v1.RoleBindingList, error) + + // Watch will start watching resources. Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.RoleBinding, err error) } +// RoleBindingCache interface for retrieving RoleBinding resources in memory. type RoleBindingCache interface { + // Get returns the resources with the specified name from the cache. Get(namespace, name string) (*v1.RoleBinding, error) + + // List will attempt to find resources from the Cache. List(namespace string, selector labels.Selector) ([]*v1.RoleBinding, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer RoleBindingIndexer) - GetByIndex(indexName, key string) ([]*v1.RoleBinding, error) -} - -type RoleBindingIndexer func(obj *v1.RoleBinding) ([]string, error) - -type roleBindingController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewRoleBindingController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) RoleBindingController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &roleBindingController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromRoleBindingHandlerToHandler(sync RoleBindingHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.RoleBinding - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.RoleBinding)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *roleBindingController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.RoleBinding)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateRoleBindingDeepCopyOnChange(client RoleBindingClient, obj *v1.RoleBinding, handler func(obj *v1.RoleBinding) (*v1.RoleBinding, error)) (*v1.RoleBinding, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *roleBindingController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} -func (c *roleBindingController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *roleBindingController) OnChange(ctx context.Context, name string, sync RoleBindingHandler) { - c.AddGenericHandler(ctx, name, FromRoleBindingHandlerToHandler(sync)) -} - -func (c *roleBindingController) OnRemove(ctx context.Context, name string, sync RoleBindingHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromRoleBindingHandlerToHandler(sync))) -} - -func (c *roleBindingController) Enqueue(namespace, name string) { - c.controller.Enqueue(namespace, name) -} - -func (c *roleBindingController) EnqueueAfter(namespace, name string, duration time.Duration) { - c.controller.EnqueueAfter(namespace, name, duration) -} - -func (c *roleBindingController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *roleBindingController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *roleBindingController) Cache() RoleBindingCache { - return &roleBindingCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *roleBindingController) Create(obj *v1.RoleBinding) (*v1.RoleBinding, error) { - result := &v1.RoleBinding{} - return result, c.client.Create(context.TODO(), obj.Namespace, obj, result, metav1.CreateOptions{}) -} - -func (c *roleBindingController) Update(obj *v1.RoleBinding) (*v1.RoleBinding, error) { - result := &v1.RoleBinding{} - return result, c.client.Update(context.TODO(), obj.Namespace, obj, result, metav1.UpdateOptions{}) -} - -func (c *roleBindingController) Delete(namespace, name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), namespace, name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.RoleBinding, error) } -func (c *roleBindingController) Get(namespace, name string, options metav1.GetOptions) (*v1.RoleBinding, error) { - result := &v1.RoleBinding{} - return result, c.client.Get(context.TODO(), namespace, name, result, options) -} +// RoleBindingHandler is function for performing any potential modifications to a RoleBinding resource. +type RoleBindingHandler func(string, *v1.RoleBinding) (*v1.RoleBinding, error) -func (c *roleBindingController) List(namespace string, opts metav1.ListOptions) (*v1.RoleBindingList, error) { - result := &v1.RoleBindingList{} - return result, c.client.List(context.TODO(), namespace, result, opts) -} +// RoleBindingIndexer computes a set of indexed values for the provided object. +type RoleBindingIndexer func(obj *v1.RoleBinding) ([]string, error) -func (c *roleBindingController) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), namespace, opts) +// RoleBindingGenericController wraps wrangler/pkg/generic.Controller so that the function definitions adhere to RoleBindingController interface. +type RoleBindingGenericController struct { + generic.ControllerInterface[*v1.RoleBinding, *v1.RoleBindingList] } -func (c *roleBindingController) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (*v1.RoleBinding, error) { - result := &v1.RoleBinding{} - return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *RoleBindingGenericController) OnChange(ctx context.Context, name string, sync RoleBindingHandler) { + c.ControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.RoleBinding](sync)) } -type roleBindingCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *RoleBindingGenericController) OnRemove(ctx context.Context, name string, sync RoleBindingHandler) { + c.ControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.RoleBinding](sync)) } -func (c *roleBindingCache) Get(namespace, name string) (*v1.RoleBinding, error) { - obj, exists, err := c.indexer.GetByKey(namespace + "/" + name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *RoleBindingGenericController) Cache() RoleBindingCache { + return &RoleBindingGenericCache{ + c.ControllerInterface.Cache(), } - return obj.(*v1.RoleBinding), nil -} - -func (c *roleBindingCache) List(namespace string, selector labels.Selector) (ret []*v1.RoleBinding, err error) { - - err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { - ret = append(ret, m.(*v1.RoleBinding)) - }) - - return ret, err } -func (c *roleBindingCache) AddIndexer(indexName string, indexer RoleBindingIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.RoleBinding)) - }, - })) +// RoleBindingGenericCache wraps wrangler/pkg/generic.Cache so the function definitions adhere to RoleBindingCache interface. +type RoleBindingGenericCache struct { + generic.CacheInterface[*v1.RoleBinding] } -func (c *roleBindingCache) GetByIndex(indexName, key string) (result []*v1.RoleBinding, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.RoleBinding, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.RoleBinding)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c RoleBindingGenericCache) AddIndexer(indexName string, indexer RoleBindingIndexer) { + c.CacheInterface.AddIndexer(indexName, generic.Indexer[*v1.RoleBinding](indexer)) } diff --git a/pkg/generated/controllers/storage/v1/interface.go b/pkg/generated/controllers/storage/v1/interface.go index cd8c04ad..02a43dfa 100644 --- a/pkg/generated/controllers/storage/v1/interface.go +++ b/pkg/generated/controllers/storage/v1/interface.go @@ -20,6 +20,7 @@ package v1 import ( "github.com/rancher/lasso/pkg/controller" + "github.com/rancher/wrangler/pkg/generic" "github.com/rancher/wrangler/pkg/schemes" v1 "k8s.io/api/storage/v1" "k8s.io/apimachinery/pkg/runtime/schema" @@ -43,6 +44,8 @@ type version struct { controllerFactory controller.SharedControllerFactory } -func (c *version) StorageClass() StorageClassController { - return NewStorageClassController(schema.GroupVersionKind{Group: "storage.k8s.io", Version: "v1", Kind: "StorageClass"}, "storageclasses", false, c.controllerFactory) +func (v *version) StorageClass() StorageClassController { + return &StorageClassGenericController{ + generic.NewNonNamespacedController[*v1.StorageClass, *v1.StorageClassList](schema.GroupVersionKind{Group: "storage.k8s.io", Version: "v1", Kind: "StorageClass"}, "storageclasses", v.controllerFactory), + } } diff --git a/pkg/generated/controllers/storage/v1/storageclass.go b/pkg/generated/controllers/storage/v1/storageclass.go index 60b1a834..7d641971 100644 --- a/pkg/generated/controllers/storage/v1/storageclass.go +++ b/pkg/generated/controllers/storage/v1/storageclass.go @@ -22,235 +22,111 @@ import ( "context" "time" - "github.com/rancher/lasso/pkg/client" - "github.com/rancher/lasso/pkg/controller" "github.com/rancher/wrangler/pkg/generic" v1 "k8s.io/api/storage/v1" - "k8s.io/apimachinery/pkg/api/equality" - "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" - "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/types" - utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/watch" - "k8s.io/client-go/tools/cache" ) -type StorageClassHandler func(string, *v1.StorageClass) (*v1.StorageClass, error) - +// StorageClassController interface for managing StorageClass resources. type StorageClassController interface { generic.ControllerMeta StorageClassClient + // OnChange runs the given handler when the controller detects a resource was changed. OnChange(ctx context.Context, name string, sync StorageClassHandler) + + // OnRemove runs the given handler when the controller detects a resource was changed. OnRemove(ctx context.Context, name string, sync StorageClassHandler) + + // Enqueue adds the resource with the given name to the worker queue of the controller. Enqueue(name string) + + // EnqueueAfter runs Enqueue after the provided duration. EnqueueAfter(name string, duration time.Duration) + // Cache returns a cache for the resource type T. Cache() StorageClassCache } +// StorageClassClient interface for managing StorageClass resources in Kubernetes. type StorageClassClient interface { + // Create creates a new object and return the newly created Object or an error. Create(*v1.StorageClass) (*v1.StorageClass, error) + + // Update updates the object and return the newly updated Object or an error. Update(*v1.StorageClass) (*v1.StorageClass, error) + // Delete deletes the Object in the given name. Delete(name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. Get(name string, options metav1.GetOptions) (*v1.StorageClass, error) + + // List will attempt to find multiple resources. List(opts metav1.ListOptions) (*v1.StorageClassList, error) + + // Watch will start watching resources. Watch(opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1.StorageClass, err error) } +// StorageClassCache interface for retrieving StorageClass resources in memory. type StorageClassCache interface { + // Get returns the resources with the specified name from the cache. Get(name string) (*v1.StorageClass, error) + + // List will attempt to find resources from the Cache. List(selector labels.Selector) ([]*v1.StorageClass, error) + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. AddIndexer(indexName string, indexer StorageClassIndexer) - GetByIndex(indexName, key string) ([]*v1.StorageClass, error) -} - -type StorageClassIndexer func(obj *v1.StorageClass) ([]string, error) - -type storageClassController struct { - controller controller.SharedController - client *client.Client - gvk schema.GroupVersionKind - groupResource schema.GroupResource -} - -func NewStorageClassController(gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) StorageClassController { - c := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) - return &storageClassController{ - controller: c, - client: c.Client(), - gvk: gvk, - groupResource: schema.GroupResource{ - Group: gvk.Group, - Resource: resource, - }, - } -} - -func FromStorageClassHandlerToHandler(sync StorageClassHandler) generic.Handler { - return func(key string, obj runtime.Object) (ret runtime.Object, err error) { - var v *v1.StorageClass - if obj == nil { - v, err = sync(key, nil) - } else { - v, err = sync(key, obj.(*v1.StorageClass)) - } - if v == nil { - return nil, err - } - return v, err - } -} - -func (c *storageClassController) Updater() generic.Updater { - return func(obj runtime.Object) (runtime.Object, error) { - newObj, err := c.Update(obj.(*v1.StorageClass)) - if newObj == nil { - return nil, err - } - return newObj, err - } -} - -func UpdateStorageClassDeepCopyOnChange(client StorageClassClient, obj *v1.StorageClass, handler func(obj *v1.StorageClass) (*v1.StorageClass, error)) (*v1.StorageClass, error) { - if obj == nil { - return obj, nil - } - - copyObj := obj.DeepCopy() - newObj, err := handler(copyObj) - if newObj != nil { - copyObj = newObj - } - if obj.ResourceVersion == copyObj.ResourceVersion && !equality.Semantic.DeepEqual(obj, copyObj) { - return client.Update(copyObj) - } - - return copyObj, err -} - -func (c *storageClassController) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { - c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) -} -func (c *storageClassController) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), handler)) -} - -func (c *storageClassController) OnChange(ctx context.Context, name string, sync StorageClassHandler) { - c.AddGenericHandler(ctx, name, FromStorageClassHandlerToHandler(sync)) -} - -func (c *storageClassController) OnRemove(ctx context.Context, name string, sync StorageClassHandler) { - c.AddGenericHandler(ctx, name, generic.NewRemoveHandler(name, c.Updater(), FromStorageClassHandlerToHandler(sync))) -} - -func (c *storageClassController) Enqueue(name string) { - c.controller.Enqueue("", name) -} - -func (c *storageClassController) EnqueueAfter(name string, duration time.Duration) { - c.controller.EnqueueAfter("", name, duration) -} - -func (c *storageClassController) Informer() cache.SharedIndexInformer { - return c.controller.Informer() -} - -func (c *storageClassController) GroupVersionKind() schema.GroupVersionKind { - return c.gvk -} - -func (c *storageClassController) Cache() StorageClassCache { - return &storageClassCache{ - indexer: c.Informer().GetIndexer(), - resource: c.groupResource, - } -} - -func (c *storageClassController) Create(obj *v1.StorageClass) (*v1.StorageClass, error) { - result := &v1.StorageClass{} - return result, c.client.Create(context.TODO(), "", obj, result, metav1.CreateOptions{}) -} - -func (c *storageClassController) Update(obj *v1.StorageClass) (*v1.StorageClass, error) { - result := &v1.StorageClass{} - return result, c.client.Update(context.TODO(), "", obj, result, metav1.UpdateOptions{}) -} - -func (c *storageClassController) Delete(name string, options *metav1.DeleteOptions) error { - if options == nil { - options = &metav1.DeleteOptions{} - } - return c.client.Delete(context.TODO(), "", name, *options) + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]*v1.StorageClass, error) } -func (c *storageClassController) Get(name string, options metav1.GetOptions) (*v1.StorageClass, error) { - result := &v1.StorageClass{} - return result, c.client.Get(context.TODO(), "", name, result, options) -} +// StorageClassHandler is function for performing any potential modifications to a StorageClass resource. +type StorageClassHandler func(string, *v1.StorageClass) (*v1.StorageClass, error) -func (c *storageClassController) List(opts metav1.ListOptions) (*v1.StorageClassList, error) { - result := &v1.StorageClassList{} - return result, c.client.List(context.TODO(), "", result, opts) -} +// StorageClassIndexer computes a set of indexed values for the provided object. +type StorageClassIndexer func(obj *v1.StorageClass) ([]string, error) -func (c *storageClassController) Watch(opts metav1.ListOptions) (watch.Interface, error) { - return c.client.Watch(context.TODO(), "", opts) +// StorageClassGenericController wraps wrangler/pkg/generic.NonNamespacedController so that the function definitions adhere to StorageClassController interface. +type StorageClassGenericController struct { + generic.NonNamespacedControllerInterface[*v1.StorageClass, *v1.StorageClassList] } -func (c *storageClassController) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (*v1.StorageClass, error) { - result := &v1.StorageClass{} - return result, c.client.Patch(context.TODO(), "", name, pt, data, result, metav1.PatchOptions{}, subresources...) +// OnChange runs the given resource handler when the controller detects a resource was changed. +func (c *StorageClassGenericController) OnChange(ctx context.Context, name string, sync StorageClassHandler) { + c.NonNamespacedControllerInterface.OnChange(ctx, name, generic.ObjectHandler[*v1.StorageClass](sync)) } -type storageClassCache struct { - indexer cache.Indexer - resource schema.GroupResource +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *StorageClassGenericController) OnRemove(ctx context.Context, name string, sync StorageClassHandler) { + c.NonNamespacedControllerInterface.OnRemove(ctx, name, generic.ObjectHandler[*v1.StorageClass](sync)) } -func (c *storageClassCache) Get(name string) (*v1.StorageClass, error) { - obj, exists, err := c.indexer.GetByKey(name) - if err != nil { - return nil, err - } - if !exists { - return nil, errors.NewNotFound(c.resource, name) +// Cache returns a cache of resources in memory. +func (c *StorageClassGenericController) Cache() StorageClassCache { + return &StorageClassGenericCache{ + c.NonNamespacedControllerInterface.Cache(), } - return obj.(*v1.StorageClass), nil -} - -func (c *storageClassCache) List(selector labels.Selector) (ret []*v1.StorageClass, err error) { - - err = cache.ListAll(c.indexer, selector, func(m interface{}) { - ret = append(ret, m.(*v1.StorageClass)) - }) - - return ret, err } -func (c *storageClassCache) AddIndexer(indexName string, indexer StorageClassIndexer) { - utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ - indexName: func(obj interface{}) (strings []string, e error) { - return indexer(obj.(*v1.StorageClass)) - }, - })) +// StorageClassGenericCache wraps wrangler/pkg/generic.NonNamespacedCache so the function definitions adhere to StorageClassCache interface. +type StorageClassGenericCache struct { + generic.NonNamespacedCacheInterface[*v1.StorageClass] } -func (c *storageClassCache) GetByIndex(indexName, key string) (result []*v1.StorageClass, err error) { - objs, err := c.indexer.ByIndex(indexName, key) - if err != nil { - return nil, err - } - result = make([]*v1.StorageClass, 0, len(objs)) - for _, obj := range objs { - result = append(result, obj.(*v1.StorageClass)) - } - return result, nil +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c StorageClassGenericCache) AddIndexer(indexName string, indexer StorageClassIndexer) { + c.NonNamespacedCacheInterface.AddIndexer(indexName, generic.Indexer[*v1.StorageClass](indexer)) } diff --git a/pkg/generic/cache.go b/pkg/generic/cache.go new file mode 100644 index 00000000..74a92f9b --- /dev/null +++ b/pkg/generic/cache.go @@ -0,0 +1,116 @@ +package generic + +import ( + "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + utilruntime "k8s.io/apimachinery/pkg/util/runtime" + "k8s.io/client-go/tools/cache" +) + +// CacheInterface is an interface for Object retrieval from memory. +type CacheInterface[T runtime.Object] interface { + // Get returns the resources with the specified name in the given namespace from the cache. + Get(namespace, name string) (T, error) + + // List will attempt to find resources in the given namespace from the Cache. + List(namespace string, selector labels.Selector) ([]T, error) + + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. + AddIndexer(indexName string, indexer Indexer[T]) + + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]T, error) +} + +// NonNamespacedCacheInterface is an interface for non namespaced Object retrieval from memory. +type NonNamespacedCacheInterface[T runtime.Object] interface { + // Get returns the resources with the specified name from the cache. + Get(name string) (T, error) + + // List will attempt to find resources from the Cache. + List(selector labels.Selector) ([]T, error) + + // AddIndexer adds a new Indexer to the cache with the provided name. + // If you call this after you already have data in the store, the results are undefined. + AddIndexer(indexName string, indexer Indexer[T]) + + // GetByIndex returns the stored objects whose set of indexed values + // for the named index includes the given indexed value. + GetByIndex(indexName, key string) ([]T, error) +} + +// Cache is a object cache stored in memory for objects of type T. +type Cache[T runtime.Object] struct { + indexer cache.Indexer + resource schema.GroupResource +} + +// NonNamespacedCache is a Cache for objects of type T that are not namespaced. +type NonNamespacedCache[T runtime.Object] struct { + CacheInterface[T] +} + +// Get returns the resources with the specified name in the given namespace from the cache. +func (c *Cache[T]) Get(namespace, name string) (T, error) { + var nilObj T + key := name + if namespace != metav1.NamespaceAll { + key = namespace + "/" + key + } + obj, exists, err := c.indexer.GetByKey(key) + if err != nil { + return nilObj, err + } + if !exists { + return nilObj, errors.NewNotFound(c.resource, name) + } + return obj.(T), nil +} + +// List will attempt to find resources in the given namespace from the Cache. +func (c *Cache[T]) List(namespace string, selector labels.Selector) (ret []T, err error) { + err = cache.ListAllByNamespace(c.indexer, namespace, selector, func(m interface{}) { + ret = append(ret, m.(T)) + }) + + return ret, err +} + +// AddIndexer adds a new Indexer to the cache with the provided name. +// If you call this after you already have data in the store, the results are undefined. +func (c *Cache[T]) AddIndexer(indexName string, indexer Indexer[T]) { + utilruntime.Must(c.indexer.AddIndexers(map[string]cache.IndexFunc{ + indexName: func(obj interface{}) (strings []string, e error) { + return indexer(obj.(T)) + }, + })) +} + +// GetByIndex returns the stored objects whose set of indexed values +// for the named index includes the given indexed value. +func (c *Cache[T]) GetByIndex(indexName, key string) (result []T, err error) { + objs, err := c.indexer.ByIndex(indexName, key) + if err != nil { + return nil, err + } + result = make([]T, 0, len(objs)) + for _, obj := range objs { + result = append(result, obj.(T)) + } + return result, nil +} + +// Get calls Cache.Get(...) with an empty namespace parameter. +func (c *NonNamespacedCache[T]) Get(name string) (T, error) { + return c.CacheInterface.Get(metav1.NamespaceAll, name) +} + +// Get calls Cache.List(...) with an empty namespace parameter. +func (c *NonNamespacedCache[T]) List(selector labels.Selector) (ret []T, err error) { + return c.CacheInterface.List(metav1.NamespaceAll, selector) +} diff --git a/pkg/generic/controller.go b/pkg/generic/controller.go index d713e0f2..cad6b959 100644 --- a/pkg/generic/controller.go +++ b/pkg/generic/controller.go @@ -1,24 +1,373 @@ +// Package generic provides generic types and implementations for Controllers, Clients, and Caches. package generic import ( "context" + "fmt" + "reflect" + "time" + "github.com/rancher/lasso/pkg/client" "github.com/rancher/lasso/pkg/controller" - + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/tools/cache" ) +// ErrSkip notifies the caller to skip this error. var ErrSkip = controller.ErrIgnore -type Handler func(key string, obj runtime.Object) (runtime.Object, error) - +// ControllerMeta holds meta information shared by all controllers. type ControllerMeta interface { + // Informer returns the SharedIndexInformer used by this controller. Informer() cache.SharedIndexInformer + + // GroupVersionKind returns the GVK used to create this Controller. GroupVersionKind() schema.GroupVersionKind + // AddGenericHandler adds a generic handler that runs when a resource changes. AddGenericHandler(ctx context.Context, name string, handler Handler) + + // AddGenericHandler adds a generic handler that runs when a resource is removed. AddGenericRemoveHandler(ctx context.Context, name string, handler Handler) + + // Updater returns a update function that will attempt to perform an update for a specific resource type. Updater() Updater } + +// RuntimeMetaObject is an interface for a K8s Object to be used with a specific controller. +type RuntimeMetaObject interface { + comparable + runtime.Object + metav1.Object +} + +// ControllerInterface interface for managing K8s Objects. +type ControllerInterface[T runtime.Object, TList runtime.Object] interface { + ControllerMeta + ClientInterface[T, TList] + + // OnChange runs the given object handler when the controller detects a resource was changed. + OnChange(ctx context.Context, name string, sync ObjectHandler[T]) + + // OnRemove runs the given object handler when the controller detects a resource was changed. + OnRemove(ctx context.Context, name string, sync ObjectHandler[T]) + + // Enqueue adds the resource with the given name in the provided namespace to the worker queue of the controller. + Enqueue(namespace, name string) + + // EnqueueAfter runs Enqueue after the provided duration. + EnqueueAfter(namespace, name string, duration time.Duration) + + // Cache returns a cache for the resource type T. + Cache() CacheInterface[T] +} + +// NonNamespacedControllerInterface interface for managing non namespaced K8s Objects. +type NonNamespacedControllerInterface[T runtime.Object, TList runtime.Object] interface { + ControllerMeta + NonNamespacedClientInterface[T, TList] + + // OnChange runs the given object handler when the controller detects a resource was changed. + OnChange(ctx context.Context, name string, sync ObjectHandler[T]) + + // OnRemove runs the given object handler when the controller detects a resource was changed. + OnRemove(ctx context.Context, name string, sync ObjectHandler[T]) + + // Enqueue adds the resource with the given name to the worker queue of the controller. + Enqueue(name string) + + // EnqueueAfter runs Enqueue after the provided duration. + EnqueueAfter(name string, duration time.Duration) + + // Cache returns a cache for the resource type T. + Cache() NonNamespacedCacheInterface[T] +} + +// ClientInterface is an interface to performs CRUD like operations on an Objects. +type ClientInterface[T runtime.Object, TList runtime.Object] interface { + // Create creates a new object and return the newly created Object or an error. + Create(T) (T, error) + + // Update updates the object and return the newly updated Object or an error. + Update(T) (T, error) + + // UpdateStatus updates the Status field of a the object and return the newly updated Object or an error. + // Will always return an error if the object does not have a status field. + UpdateStatus(T) (T, error) + + // Delete deletes the Object in the given name and namespace. + Delete(namespace, name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the given name in the given namespace. + Get(namespace, name string, options metav1.GetOptions) (T, error) + + // List will attempt to find resources in the given namespace. + List(namespace string, opts metav1.ListOptions) (TList, error) + + // Watch will start watching resources in the given namespace. + Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name in the matching namespace. + Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (result T, err error) +} + +// NonNamespacedClientInterface is an interface to performs CRUD like operations on nonNamespaced Objects. +type NonNamespacedClientInterface[T runtime.Object, TList runtime.Object] interface { + // Create creates a new object and return the newly created Object or an error. + Create(T) (T, error) + + // Update updates the object and return the newly updated Object or an error. + Update(T) (T, error) + + // UpdateStatus updates the Status field of a the object and return the newly updated Object or an error. + // Will always return an error if the object does not have a status field. + UpdateStatus(T) (T, error) + + // Delete deletes the Object in the given name. + Delete(name string, options *metav1.DeleteOptions) error + + // Get will attempt to retrieve the resource with the specified name. + Get(name string, options metav1.GetOptions) (T, error) + + // List will attempt to find multiple resources. + List(opts metav1.ListOptions) (TList, error) + + // Watch will start watching resources. + Watch(opts metav1.ListOptions) (watch.Interface, error) + + // Patch will patch the resource with the matching name. + Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result T, err error) +} + +// ObjectHandler performs operations on the given runtime.Object and returns the new runtime.Object or an error +type Handler func(key string, obj runtime.Object) (runtime.Object, error) + +// ObjectHandler performs operations on the given object and returns the new object or an error +type ObjectHandler[T runtime.Object] func(string, T) (T, error) + +// Indexer computes a set of indexed values for the provided object. +type Indexer[T runtime.Object] func(obj T) ([]string, error) + +// FromObjectHandlerToHandler converts an ObjecHandler to a Handler. +func FromObjectHandlerToHandler[T RuntimeMetaObject](sync ObjectHandler[T]) Handler { + return func(key string, obj runtime.Object) (runtime.Object, error) { + var nilObj, retObj T + var err error + if obj == nil { + retObj, err = sync(key, nilObj) + } else { + retObj, err = sync(key, obj.(T)) + } + if retObj == nilObj { + return nil, err + } + return retObj, err + } +} + +// Controller is used to manage objects of type T. +type Controller[T RuntimeMetaObject, TList runtime.Object] struct { + controller controller.SharedController + client *client.Client + gvk schema.GroupVersionKind + groupResource schema.GroupResource + objType reflect.Type + objListType reflect.Type +} + +// NonNamespacedController is a Controller for non namespaced resources. This controller provides similar function definitions as Controller except the namespace parameter is omitted. +type NonNamespacedController[T RuntimeMetaObject, TList runtime.Object] struct { + Controller[T, TList] +} + +// NewController creates a new controller for the given Object type and ObjectList type. +func NewController[T RuntimeMetaObject, TList runtime.Object](gvk schema.GroupVersionKind, resource string, namespaced bool, controller controller.SharedControllerFactory) *Controller[T, TList] { + sharedCtrl := controller.ForResourceKind(gvk.GroupVersion().WithResource(resource), gvk.Kind, namespaced) + var obj T + objPtrType := reflect.TypeOf(obj) + if objPtrType.Kind() != reflect.Pointer { + panic(fmt.Sprintf("Controller requires Object T to be a pointer not %v", objPtrType)) + } + var objList TList + objListPtrType := reflect.TypeOf(objList) + if objListPtrType.Kind() != reflect.Pointer { + panic(fmt.Sprintf("Controller requires Object TList to be a pointer not %v", objListPtrType)) + } + return &Controller[T, TList]{ + controller: sharedCtrl, + client: sharedCtrl.Client(), + gvk: gvk, + groupResource: schema.GroupResource{ + Group: gvk.Group, + Resource: resource, + }, + objType: objPtrType.Elem(), + objListType: objListPtrType.Elem(), + } +} + +// Updater creates a new Updater for the Object type T. +func (c *Controller[T, TList]) Updater() Updater { + var nilObj T + return func(obj runtime.Object) (runtime.Object, error) { + newObj, err := c.Update(obj.(T)) + if newObj == nilObj { + return nil, err + } + return newObj, err + } +} + +// AddGenericHandler runs the given handler when the controller detects an object was changed. +func (c *Controller[T, TList]) AddGenericHandler(ctx context.Context, name string, handler Handler) { + c.controller.RegisterHandler(ctx, name, controller.SharedControllerHandlerFunc(handler)) +} + +// AddGenericRemoveHandler runs the given handler when the controller detects an object was removed. +func (c *Controller[T, TList]) AddGenericRemoveHandler(ctx context.Context, name string, handler Handler) { + c.AddGenericHandler(ctx, name, NewRemoveHandler(name, c.Updater(), handler)) +} + +// OnChange runs the given object handler when the controller detects a resource was changed. +func (c *Controller[T, TList]) OnChange(ctx context.Context, name string, sync ObjectHandler[T]) { + c.AddGenericHandler(ctx, name, FromObjectHandlerToHandler(sync)) +} + +// OnRemove runs the given object handler when the controller detects a resource was changed. +func (c *Controller[T, TList]) OnRemove(ctx context.Context, name string, sync ObjectHandler[T]) { + c.AddGenericHandler(ctx, name, NewRemoveHandler(name, c.Updater(), FromObjectHandlerToHandler(sync))) +} + +// Enqueue adds the resource with the given name in the provided namespace to the worker queue of the controller. +func (c *Controller[T, TList]) Enqueue(namespace, name string) { + c.controller.Enqueue(namespace, name) +} + +// EnqueueAfter runs Enqueue after the provided duration. +func (c *Controller[T, TList]) EnqueueAfter(namespace, name string, duration time.Duration) { + c.controller.EnqueueAfter(namespace, name, duration) +} + +// Informer returns the SharedIndexInformer used by this controller. +func (c *Controller[T, TList]) Informer() cache.SharedIndexInformer { + return c.controller.Informer() +} + +// GroupVersionKind returns the GVK used to create this Controller. +func (c *Controller[T, TList]) GroupVersionKind() schema.GroupVersionKind { + return c.gvk +} + +// Cache returns a cache for the objects T. +func (c *Controller[T, TList]) Cache() CacheInterface[T] { + return &Cache[T]{ + indexer: c.Informer().GetIndexer(), + resource: c.groupResource, + } +} + +// Create creates a new object and return the newly created Object or an error. +func (c *Controller[T, TList]) Create(obj T) (T, error) { + result := reflect.New(c.objType).Interface().(T) + return result, c.client.Create(context.TODO(), obj.GetNamespace(), obj, result, metav1.CreateOptions{}) +} + +// Update updates the object and return the newly updated Object or an error. +func (c *Controller[T, TList]) Update(obj T) (T, error) { + result := reflect.New(c.objType).Interface().(T) + return result, c.client.Update(context.TODO(), obj.GetNamespace(), obj, result, metav1.UpdateOptions{}) +} + +// UpdateStatus updates the Status field of a the object and return the newly updated Object or an error. +// Will always return an error if the object does not have a status field. +func (c *Controller[T, TList]) UpdateStatus(obj T) (T, error) { + result := reflect.New(c.objType).Interface().(T) + return result, c.client.UpdateStatus(context.TODO(), obj.GetNamespace(), obj, result, metav1.UpdateOptions{}) +} + +// Delete deletes the Object in the given name and Namespace. +func (c *Controller[T, TList]) Delete(namespace, name string, options *metav1.DeleteOptions) error { + if options == nil { + options = &metav1.DeleteOptions{} + } + return c.client.Delete(context.TODO(), namespace, name, *options) +} + +// Get gets returns the given resource with the given name in the provided namespace. +func (c *Controller[T, TList]) Get(namespace, name string, options metav1.GetOptions) (T, error) { + result := reflect.New(c.objType).Interface().(T) + return result, c.client.Get(context.TODO(), namespace, name, result, options) +} + +// List will attempt to find resources in the given namespace. +func (c *Controller[T, TList]) List(namespace string, opts metav1.ListOptions) (TList, error) { + result := reflect.New(c.objListType).Interface().(TList) + return result, c.client.List(context.TODO(), namespace, result, opts) +} + +// Watch will start watching resources in the given namespace. +func (c *Controller[T, TList]) Watch(namespace string, opts metav1.ListOptions) (watch.Interface, error) { + return c.client.Watch(context.TODO(), namespace, opts) +} + +// Patch will patch the resource with the matching name in the matching namespace. +func (c *Controller[T, TList]) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (T, error) { + result := reflect.New(c.objType).Interface().(T) + return result, c.client.Patch(context.TODO(), namespace, name, pt, data, result, metav1.PatchOptions{}, subresources...) +} + +// NewNonNamespacedController returns a Controller controller that is not namespaced. +// NonNamespacedController redefines specific functions to no longer accept the namespace parameter. +func NewNonNamespacedController[T RuntimeMetaObject, TList runtime.Object](gvk schema.GroupVersionKind, resource string, + controller controller.SharedControllerFactory, +) *NonNamespacedController[T, TList] { + return &NonNamespacedController[T, TList]{ + Controller: *NewController[T, TList](gvk, resource, false, controller), + } +} + +// Enqueue calls Controller.Enqueue(...) with an empty namespace parameter. +func (c *NonNamespacedController[T, TList]) Enqueue(name string) { + c.controller.Enqueue(metav1.NamespaceAll, name) +} + +// EnqueueAfter calls Controller.EnqueueAfter(...) with an empty namespace parameter. +func (c *NonNamespacedController[T, TList]) EnqueueAfter(name string, duration time.Duration) { + c.controller.EnqueueAfter(metav1.NamespaceAll, name, duration) +} + +// Delete calls Controller.Delete(...) with an empty namespace parameter. +func (c *NonNamespacedController[T, TList]) Delete(name string, options *metav1.DeleteOptions) error { + return c.Controller.Delete(metav1.NamespaceAll, name, options) +} + +// Get calls Controller.Get(...) with an empty namespace parameter. +func (c *NonNamespacedController[T, TList]) Get(name string, options metav1.GetOptions) (T, error) { + return c.Controller.Get(metav1.NamespaceAll, name, options) +} + +// List calls Controller.List(...) with an empty namespace parameter. +func (c *NonNamespacedController[T, TList]) List(opts metav1.ListOptions) (TList, error) { + return c.Controller.List(metav1.NamespaceAll, opts) +} + +// Watch calls Controller.Watch(...) with an empty namespace parameter. +func (c *NonNamespacedController[T, TList]) Watch(opts metav1.ListOptions) (watch.Interface, error) { + return c.Controller.Watch(metav1.NamespaceAll, opts) +} + +// Patch calls the Controller.Patch(...) with an empty namespace parameter. +func (c *NonNamespacedController[T, TList]) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (T, error) { + return c.Controller.Patch(metav1.NamespaceAll, name, pt, data, subresources...) +} + +// Cache calls Controller.Cache(...) and wraps the result in a new NonNamespacedCache. +func (c *NonNamespacedController[T, TList]) Cache() NonNamespacedCacheInterface[T] { + return &NonNamespacedCache[T]{ + CacheInterface: c.Controller.Cache(), + } +} diff --git a/pkg/generic/fake/README.md b/pkg/generic/fake/README.md new file mode 100644 index 00000000..e58dce74 --- /dev/null +++ b/pkg/generic/fake/README.md @@ -0,0 +1,65 @@ +# Generic Controller, Client, and Cache Mocks + +This package leverages https://github.com/golang/mock for using generic mocks in tests. +[gomock](https://pkg.go.dev/github.com/golang/mock/gomock) holds more specific information on different ways to use gomock in test. + +## Usage +This package has four entry points for creating a mock controller, client, or cache interface.
+ Note: A mock controller will implement both a generic.ControllerInterface and a generic.ClientInterface. +- `NewMockControllerInterface[T runtime.Object, TList runtime.Object](*gomock.Controller)` +- `NewMockNonNamespacedControllerInterface[T runtime.Object, TList runtime.Object](*gomock.Controller)` +- `NewCacheInterface[T runtime.Object](*gomock.Controller)` +- `NewNonNamespaceCacheInterface[T runtime.Object](*gomock.Controller)` + + +Example use of generic/fake with a generated Deployment Controller. +``` golang +// Generated controller interface to mock. +type DeploymentController interface { + generic.ControllerMeta + DeploymentClient + OnChange(ctx context.Context, name string, sync DeploymentHandler) + OnRemove(ctx context.Context, name string, sync DeploymentHandler) + Enqueue(namespace, name string) + EnqueueAfter(namespace, name string, duration time.Duration) + Cache() DeploymentCaches +} +``` +``` golang +// Example Test Function +import ( + "testing" + + "github.com/golang/mock/gomock" + wranglerv1 "github.com/rancher/wrangler/pkg/generated/controllers/rbac/v1" + "github.com/rancher/wrangler/pkg/generic/fake" + v1 "k8s.io/api/apps/v1" +) + +func TestController(t *testing.T){ + // Create gomock controller. This is used by the gomock library. + gomockCtrl := gomock.NewController(t) + + // Create a new Generic Controller Mock with type apps1.Deployment. + deployMock := fake.NewMockControllerInterface[*v1.Deployment, *v1.DeploymentList](ctrl) + + // Wrap our mocked genericController around the type specific DeploymentGenericController + // which satisfies DeploymentController interface + testDeployCtrl := wranglerv1.DeploymentGenericController{deployMock} + + // Define expected calls to our mock controller using gomock. + deployMock.EXPECT().Enqueue("test-namespace", "test-name").AnyTimes() + + // Start Test Code. + // . + // . + // . + + // Test calls Enqueue with expected parameters nothing happens. + testDeployCtrl.Enqueue("test-namespace", "test-name") + + // Test calls Enqueue with unexpected parameters. + // gomock will fail the test because it did not expect the call. + testDeployCtrl.Enqueue("unexpected-namespace", "unexpected-name") +} +``` diff --git a/pkg/generic/fake/controller.go b/pkg/generic/fake/controller.go new file mode 100644 index 00000000..10d05ded --- /dev/null +++ b/pkg/generic/fake/controller.go @@ -0,0 +1,1022 @@ +// Package fake is used to create github.com/golang/mock compatible mocks for generic client, caches, and controller interfaces. +package fake + +import ( + "context" + "reflect" + "time" + + "github.com/golang/mock/gomock" + "github.com/rancher/wrangler/pkg/generic" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/watch" + "k8s.io/client-go/tools/cache" +) + +// MockControllerInterface is a mock of ControllerInterface interface. +type MockControllerInterface[T runtime.Object, TList runtime.Object] struct { + ctrl *gomock.Controller + recorder *MockControllerInterfaceMockRecorder[T, TList] +} + +// MockControllerInterfaceMockRecorder is the mock recorder for MockControllerInterface. +type MockControllerInterfaceMockRecorder[T runtime.Object, TList runtime.Object] struct { + mock *MockControllerInterface[T, TList] +} + +// NewMockControllerInterface creates a new mock instance. +func NewMockControllerInterface[T runtime.Object, TList runtime.Object](ctrl *gomock.Controller) *MockControllerInterface[T, TList] { + mock := &MockControllerInterface[T, TList]{ctrl: ctrl} + mock.recorder = &MockControllerInterfaceMockRecorder[T, TList]{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockControllerInterface[T, TList]) EXPECT() *MockControllerInterfaceMockRecorder[T, TList] { + return m.recorder +} + +// AddGenericHandler mocks base method. +func (m *MockControllerInterface[T, TList]) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddGenericHandler", ctx, name, handler) +} + +// AddGenericHandler indicates an expected call of AddGenericHandler. +func (mr *MockControllerInterfaceMockRecorder[T, TList]) AddGenericHandler(ctx, name, handler interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddGenericHandler", reflect.TypeOf((*MockControllerInterface[T, TList])(nil).AddGenericHandler), ctx, name, handler) +} + +// AddGenericRemoveHandler mocks base method. +func (m *MockControllerInterface[T, TList]) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddGenericRemoveHandler", ctx, name, handler) +} + +// AddGenericRemoveHandler indicates an expected call of AddGenericRemoveHandler. +func (mr *MockControllerInterfaceMockRecorder[T, TList]) AddGenericRemoveHandler(ctx, name, handler interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddGenericRemoveHandler", reflect.TypeOf((*MockControllerInterface[T, TList])(nil).AddGenericRemoveHandler), ctx, name, handler) +} + +// Cache mocks base method. +func (m *MockControllerInterface[T, TList]) Cache() generic.CacheInterface[T] { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Cache") + ret0, _ := ret[0].(generic.CacheInterface[T]) + return ret0 +} + +// Cache indicates an expected call of Cache. +func (mr *MockControllerInterfaceMockRecorder[T, TList]) Cache() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Cache", reflect.TypeOf((*MockControllerInterface[T, TList])(nil).Cache)) +} + +// Create mocks base method. +func (m *MockControllerInterface[T, TList]) Create(arg0 T) (T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Create", arg0) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Create indicates an expected call of Create. +func (mr *MockControllerInterfaceMockRecorder[T, TList]) Create(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockControllerInterface[T, TList])(nil).Create), arg0) +} + +// Delete mocks base method. +func (m *MockControllerInterface[T, TList]) Delete(namespace, name string, options *v1.DeleteOptions) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Delete", namespace, name, options) + ret0, _ := ret[0].(error) + return ret0 +} + +// Delete indicates an expected call of Delete. +func (mr *MockControllerInterfaceMockRecorder[T, TList]) Delete(namespace, name, options interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockControllerInterface[T, TList])(nil).Delete), namespace, name, options) +} + +// Enqueue mocks base method. +func (m *MockControllerInterface[T, TList]) Enqueue(namespace, name string) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "Enqueue", namespace, name) +} + +// Enqueue indicates an expected call of Enqueue. +func (mr *MockControllerInterfaceMockRecorder[T, TList]) Enqueue(namespace, name interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Enqueue", reflect.TypeOf((*MockControllerInterface[T, TList])(nil).Enqueue), namespace, name) +} + +// EnqueueAfter mocks base method. +func (m *MockControllerInterface[T, TList]) EnqueueAfter(namespace, name string, duration time.Duration) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "EnqueueAfter", namespace, name, duration) +} + +// EnqueueAfter indicates an expected call of EnqueueAfter. +func (mr *MockControllerInterfaceMockRecorder[T, TList]) EnqueueAfter(namespace, name, duration interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnqueueAfter", reflect.TypeOf((*MockControllerInterface[T, TList])(nil).EnqueueAfter), namespace, name, duration) +} + +// Get mocks base method. +func (m *MockControllerInterface[T, TList]) Get(namespace, name string, options v1.GetOptions) (T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Get", namespace, name, options) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Get indicates an expected call of Get. +func (mr *MockControllerInterfaceMockRecorder[T, TList]) Get(namespace, name, options interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockControllerInterface[T, TList])(nil).Get), namespace, name, options) +} + +// GroupVersionKind mocks base method. +func (m *MockControllerInterface[T, TList]) GroupVersionKind() schema.GroupVersionKind { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GroupVersionKind") + ret0, _ := ret[0].(schema.GroupVersionKind) + return ret0 +} + +// GroupVersionKind indicates an expected call of GroupVersionKind. +func (mr *MockControllerInterfaceMockRecorder[T, TList]) GroupVersionKind() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupVersionKind", reflect.TypeOf((*MockControllerInterface[T, TList])(nil).GroupVersionKind)) +} + +// Informer mocks base method. +func (m *MockControllerInterface[T, TList]) Informer() cache.SharedIndexInformer { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Informer") + ret0, _ := ret[0].(cache.SharedIndexInformer) + return ret0 +} + +// Informer indicates an expected call of Informer. +func (mr *MockControllerInterfaceMockRecorder[T, TList]) Informer() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Informer", reflect.TypeOf((*MockControllerInterface[T, TList])(nil).Informer)) +} + +// List mocks base method. +func (m *MockControllerInterface[T, TList]) List(namespace string, opts v1.ListOptions) (TList, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "List", namespace, opts) + ret0, _ := ret[0].(TList) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// List indicates an expected call of List. +func (mr *MockControllerInterfaceMockRecorder[T, TList]) List(namespace, opts interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockControllerInterface[T, TList])(nil).List), namespace, opts) +} + +// OnChange mocks base method. +func (m *MockControllerInterface[T, TList]) OnChange(ctx context.Context, name string, sync generic.ObjectHandler[T]) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "OnChange", ctx, name, sync) +} + +// OnChange indicates an expected call of OnChange. +func (mr *MockControllerInterfaceMockRecorder[T, TList]) OnChange(ctx, name, sync interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnChange", reflect.TypeOf((*MockControllerInterface[T, TList])(nil).OnChange), ctx, name, sync) +} + +// OnRemove mocks base method. +func (m *MockControllerInterface[T, TList]) OnRemove(ctx context.Context, name string, sync generic.ObjectHandler[T]) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "OnRemove", ctx, name, sync) +} + +// OnRemove indicates an expected call of OnRemove. +func (mr *MockControllerInterfaceMockRecorder[T, TList]) OnRemove(ctx, name, sync interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnRemove", reflect.TypeOf((*MockControllerInterface[T, TList])(nil).OnRemove), ctx, name, sync) +} + +// Patch mocks base method. +func (m *MockControllerInterface[T, TList]) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (T, error) { + m.ctrl.T.Helper() + varargs := []interface{}{namespace, name, pt, data} + for _, a := range subresources { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "Patch", varargs...) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Patch indicates an expected call of Patch. +func (mr *MockControllerInterfaceMockRecorder[T, TList]) Patch(namespace, name, pt, data interface{}, subresources ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{namespace, name, pt, data}, subresources...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Patch", reflect.TypeOf((*MockControllerInterface[T, TList])(nil).Patch), varargs...) +} + +// Update mocks base method. +func (m *MockControllerInterface[T, TList]) Update(arg0 T) (T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Update", arg0) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Update indicates an expected call of Update. +func (mr *MockControllerInterfaceMockRecorder[T, TList]) Update(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockControllerInterface[T, TList])(nil).Update), arg0) +} + +// UpdateStatus mocks base method. +func (m *MockControllerInterface[T, TList]) UpdateStatus(arg0 T) (T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpdateStatus", arg0) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// UpdateStatus indicates an expected call of UpdateStatus. +func (mr *MockControllerInterfaceMockRecorder[T, TList]) UpdateStatus(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateStatus", reflect.TypeOf((*MockControllerInterface[T, TList])(nil).UpdateStatus), arg0) +} + +// Updater mocks base method. +func (m *MockControllerInterface[T, TList]) Updater() generic.Updater { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Updater") + ret0, _ := ret[0].(generic.Updater) + return ret0 +} + +// Updater indicates an expected call of Updater. +func (mr *MockControllerInterfaceMockRecorder[T, TList]) Updater() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Updater", reflect.TypeOf((*MockControllerInterface[T, TList])(nil).Updater)) +} + +// Watch mocks base method. +func (m *MockControllerInterface[T, TList]) Watch(namespace string, opts v1.ListOptions) (watch.Interface, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Watch", namespace, opts) + ret0, _ := ret[0].(watch.Interface) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Watch indicates an expected call of Watch. +func (mr *MockControllerInterfaceMockRecorder[T, TList]) Watch(namespace, opts interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Watch", reflect.TypeOf((*MockControllerInterface[T, TList])(nil).Watch), namespace, opts) +} + +// MockNonNamespacedControllerInterface is a mock of NonNamespacedControllerInterface interface. +type MockNonNamespacedControllerInterface[T runtime.Object, TList runtime.Object] struct { + ctrl *gomock.Controller + recorder *MockNonNamespacedControllerInterfaceMockRecorder[T, TList] +} + +// MockNonNamespacedControllerInterfaceMockRecorder is the mock recorder for MockNonNamespacedControllerInterface. +type MockNonNamespacedControllerInterfaceMockRecorder[T runtime.Object, TList runtime.Object] struct { + mock *MockNonNamespacedControllerInterface[T, TList] +} + +// NewMockNonNamespacedControllerInterface creates a new mock instance. +func NewMockNonNamespacedControllerInterface[T runtime.Object, TList runtime.Object](ctrl *gomock.Controller) *MockNonNamespacedControllerInterface[T, TList] { + mock := &MockNonNamespacedControllerInterface[T, TList]{ctrl: ctrl} + mock.recorder = &MockNonNamespacedControllerInterfaceMockRecorder[T, TList]{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockNonNamespacedControllerInterface[T, TList]) EXPECT() *MockNonNamespacedControllerInterfaceMockRecorder[T, TList] { + return m.recorder +} + +// AddGenericHandler mocks base method. +func (m *MockNonNamespacedControllerInterface[T, TList]) AddGenericHandler(ctx context.Context, name string, handler generic.Handler) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddGenericHandler", ctx, name, handler) +} + +// AddGenericHandler indicates an expected call of AddGenericHandler. +func (mr *MockNonNamespacedControllerInterfaceMockRecorder[T, TList]) AddGenericHandler(ctx, name, handler interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddGenericHandler", reflect.TypeOf((*MockNonNamespacedControllerInterface[T, TList])(nil).AddGenericHandler), ctx, name, handler) +} + +// AddGenericRemoveHandler mocks base method. +func (m *MockNonNamespacedControllerInterface[T, TList]) AddGenericRemoveHandler(ctx context.Context, name string, handler generic.Handler) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddGenericRemoveHandler", ctx, name, handler) +} + +// AddGenericRemoveHandler indicates an expected call of AddGenericRemoveHandler. +func (mr *MockNonNamespacedControllerInterfaceMockRecorder[T, TList]) AddGenericRemoveHandler(ctx, name, handler interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddGenericRemoveHandler", reflect.TypeOf((*MockNonNamespacedControllerInterface[T, TList])(nil).AddGenericRemoveHandler), ctx, name, handler) +} + +// Cache mocks base method. +func (m *MockNonNamespacedControllerInterface[T, TList]) Cache() generic.NonNamespacedCacheInterface[T] { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Cache") + ret0, _ := ret[0].(generic.NonNamespacedCacheInterface[T]) + return ret0 +} + +// Cache indicates an expected call of Cache. +func (mr *MockNonNamespacedControllerInterfaceMockRecorder[T, TList]) Cache() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Cache", reflect.TypeOf((*MockNonNamespacedControllerInterface[T, TList])(nil).Cache)) +} + +// Create mocks base method. +func (m *MockNonNamespacedControllerInterface[T, TList]) Create(arg0 T) (T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Create", arg0) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Create indicates an expected call of Create. +func (mr *MockNonNamespacedControllerInterfaceMockRecorder[T, TList]) Create(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockNonNamespacedControllerInterface[T, TList])(nil).Create), arg0) +} + +// Delete mocks base method. +func (m *MockNonNamespacedControllerInterface[T, TList]) Delete(name string, options *v1.DeleteOptions) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Delete", name, options) + ret0, _ := ret[0].(error) + return ret0 +} + +// Delete indicates an expected call of Delete. +func (mr *MockNonNamespacedControllerInterfaceMockRecorder[T, TList]) Delete(name, options interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockNonNamespacedControllerInterface[T, TList])(nil).Delete), name, options) +} + +// Enqueue mocks base method. +func (m *MockNonNamespacedControllerInterface[T, TList]) Enqueue(name string) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "Enqueue", name) +} + +// Enqueue indicates an expected call of Enqueue. +func (mr *MockNonNamespacedControllerInterfaceMockRecorder[T, TList]) Enqueue(name interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Enqueue", reflect.TypeOf((*MockNonNamespacedControllerInterface[T, TList])(nil).Enqueue), name) +} + +// EnqueueAfter mocks base method. +func (m *MockNonNamespacedControllerInterface[T, TList]) EnqueueAfter(name string, duration time.Duration) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "EnqueueAfter", name, duration) +} + +// EnqueueAfter indicates an expected call of EnqueueAfter. +func (mr *MockNonNamespacedControllerInterfaceMockRecorder[T, TList]) EnqueueAfter(name, duration interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "EnqueueAfter", reflect.TypeOf((*MockNonNamespacedControllerInterface[T, TList])(nil).EnqueueAfter), name, duration) +} + +// Get mocks base method. +func (m *MockNonNamespacedControllerInterface[T, TList]) Get(name string, options v1.GetOptions) (T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Get", name, options) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Get indicates an expected call of Get. +func (mr *MockNonNamespacedControllerInterfaceMockRecorder[T, TList]) Get(name, options interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockNonNamespacedControllerInterface[T, TList])(nil).Get), name, options) +} + +// GroupVersionKind mocks base method. +func (m *MockNonNamespacedControllerInterface[T, TList]) GroupVersionKind() schema.GroupVersionKind { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GroupVersionKind") + ret0, _ := ret[0].(schema.GroupVersionKind) + return ret0 +} + +// GroupVersionKind indicates an expected call of GroupVersionKind. +func (mr *MockNonNamespacedControllerInterfaceMockRecorder[T, TList]) GroupVersionKind() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GroupVersionKind", reflect.TypeOf((*MockNonNamespacedControllerInterface[T, TList])(nil).GroupVersionKind)) +} + +// Informer mocks base method. +func (m *MockNonNamespacedControllerInterface[T, TList]) Informer() cache.SharedIndexInformer { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Informer") + ret0, _ := ret[0].(cache.SharedIndexInformer) + return ret0 +} + +// Informer indicates an expected call of Informer. +func (mr *MockNonNamespacedControllerInterfaceMockRecorder[T, TList]) Informer() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Informer", reflect.TypeOf((*MockNonNamespacedControllerInterface[T, TList])(nil).Informer)) +} + +// List mocks base method. +func (m *MockNonNamespacedControllerInterface[T, TList]) List(opts v1.ListOptions) (TList, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "List", opts) + ret0, _ := ret[0].(TList) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// List indicates an expected call of List. +func (mr *MockNonNamespacedControllerInterfaceMockRecorder[T, TList]) List(opts interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockNonNamespacedControllerInterface[T, TList])(nil).List), opts) +} + +// OnChange mocks base method. +func (m *MockNonNamespacedControllerInterface[T, TList]) OnChange(ctx context.Context, name string, sync generic.ObjectHandler[T]) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "OnChange", ctx, name, sync) +} + +// OnChange indicates an expected call of OnChange. +func (mr *MockNonNamespacedControllerInterfaceMockRecorder[T, TList]) OnChange(ctx, name, sync interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnChange", reflect.TypeOf((*MockNonNamespacedControllerInterface[T, TList])(nil).OnChange), ctx, name, sync) +} + +// OnRemove mocks base method. +func (m *MockNonNamespacedControllerInterface[T, TList]) OnRemove(ctx context.Context, name string, sync generic.ObjectHandler[T]) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "OnRemove", ctx, name, sync) +} + +// OnRemove indicates an expected call of OnRemove. +func (mr *MockNonNamespacedControllerInterfaceMockRecorder[T, TList]) OnRemove(ctx, name, sync interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "OnRemove", reflect.TypeOf((*MockNonNamespacedControllerInterface[T, TList])(nil).OnRemove), ctx, name, sync) +} + +// Patch mocks base method. +func (m *MockNonNamespacedControllerInterface[T, TList]) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (T, error) { + m.ctrl.T.Helper() + varargs := []interface{}{name, pt, data} + for _, a := range subresources { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "Patch", varargs...) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Patch indicates an expected call of Patch. +func (mr *MockNonNamespacedControllerInterfaceMockRecorder[T, TList]) Patch(name, pt, data interface{}, subresources ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{name, pt, data}, subresources...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Patch", reflect.TypeOf((*MockNonNamespacedControllerInterface[T, TList])(nil).Patch), varargs...) +} + +// Update mocks base method. +func (m *MockNonNamespacedControllerInterface[T, TList]) Update(arg0 T) (T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Update", arg0) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Update indicates an expected call of Update. +func (mr *MockNonNamespacedControllerInterfaceMockRecorder[T, TList]) Update(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockNonNamespacedControllerInterface[T, TList])(nil).Update), arg0) +} + +// UpdateStatus mocks base method. +func (m *MockNonNamespacedControllerInterface[T, TList]) UpdateStatus(arg0 T) (T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpdateStatus", arg0) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// UpdateStatus indicates an expected call of UpdateStatus. +func (mr *MockNonNamespacedControllerInterfaceMockRecorder[T, TList]) UpdateStatus(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateStatus", reflect.TypeOf((*MockNonNamespacedControllerInterface[T, TList])(nil).UpdateStatus), arg0) +} + +// Updater mocks base method. +func (m *MockNonNamespacedControllerInterface[T, TList]) Updater() generic.Updater { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Updater") + ret0, _ := ret[0].(generic.Updater) + return ret0 +} + +// Updater indicates an expected call of Updater. +func (mr *MockNonNamespacedControllerInterfaceMockRecorder[T, TList]) Updater() *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Updater", reflect.TypeOf((*MockNonNamespacedControllerInterface[T, TList])(nil).Updater)) +} + +// Watch mocks base method. +func (m *MockNonNamespacedControllerInterface[T, TList]) Watch(opts v1.ListOptions) (watch.Interface, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Watch", opts) + ret0, _ := ret[0].(watch.Interface) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Watch indicates an expected call of Watch. +func (mr *MockNonNamespacedControllerInterfaceMockRecorder[T, TList]) Watch(opts interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Watch", reflect.TypeOf((*MockNonNamespacedControllerInterface[T, TList])(nil).Watch), opts) +} + +// MockClientInterface is a mock of ClientInterface interface. +type MockClientInterface[T runtime.Object, TList runtime.Object] struct { + ctrl *gomock.Controller + recorder *MockClientInterfaceMockRecorder[T, TList] +} + +// MockClientInterfaceMockRecorder is the mock recorder for MockClientInterface. +type MockClientInterfaceMockRecorder[T runtime.Object, TList runtime.Object] struct { + mock *MockClientInterface[T, TList] +} + +// NewMockClientInterface creates a new mock instance. +func NewMockClientInterface[T runtime.Object, TList runtime.Object](ctrl *gomock.Controller) *MockClientInterface[T, TList] { + mock := &MockClientInterface[T, TList]{ctrl: ctrl} + mock.recorder = &MockClientInterfaceMockRecorder[T, TList]{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockClientInterface[T, TList]) EXPECT() *MockClientInterfaceMockRecorder[T, TList] { + return m.recorder +} + +// Create mocks base method. +func (m *MockClientInterface[T, TList]) Create(arg0 T) (T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Create", arg0) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Create indicates an expected call of Create. +func (mr *MockClientInterfaceMockRecorder[T, TList]) Create(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockClientInterface[T, TList])(nil).Create), arg0) +} + +// Delete mocks base method. +func (m *MockClientInterface[T, TList]) Delete(namespace, name string, options *v1.DeleteOptions) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Delete", namespace, name, options) + ret0, _ := ret[0].(error) + return ret0 +} + +// Delete indicates an expected call of Delete. +func (mr *MockClientInterfaceMockRecorder[T, TList]) Delete(namespace, name, options interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockClientInterface[T, TList])(nil).Delete), namespace, name, options) +} + +// Get mocks base method. +func (m *MockClientInterface[T, TList]) Get(namespace, name string, options v1.GetOptions) (T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Get", namespace, name, options) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Get indicates an expected call of Get. +func (mr *MockClientInterfaceMockRecorder[T, TList]) Get(namespace, name, options interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockClientInterface[T, TList])(nil).Get), namespace, name, options) +} + +// List mocks base method. +func (m *MockClientInterface[T, TList]) List(namespace string, opts v1.ListOptions) (TList, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "List", namespace, opts) + ret0, _ := ret[0].(TList) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// List indicates an expected call of List. +func (mr *MockClientInterfaceMockRecorder[T, TList]) List(namespace, opts interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockClientInterface[T, TList])(nil).List), namespace, opts) +} + +// Patch mocks base method. +func (m *MockClientInterface[T, TList]) Patch(namespace, name string, pt types.PatchType, data []byte, subresources ...string) (T, error) { + m.ctrl.T.Helper() + varargs := []interface{}{namespace, name, pt, data} + for _, a := range subresources { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "Patch", varargs...) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Patch indicates an expected call of Patch. +func (mr *MockClientInterfaceMockRecorder[T, TList]) Patch(namespace, name, pt, data interface{}, subresources ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{namespace, name, pt, data}, subresources...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Patch", reflect.TypeOf((*MockClientInterface[T, TList])(nil).Patch), varargs...) +} + +// Update mocks base method. +func (m *MockClientInterface[T, TList]) Update(arg0 T) (T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Update", arg0) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Update indicates an expected call of Update. +func (mr *MockClientInterfaceMockRecorder[T, TList]) Update(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockClientInterface[T, TList])(nil).Update), arg0) +} + +// UpdateStatus mocks base method. +func (m *MockClientInterface[T, TList]) UpdateStatus(arg0 T) (T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpdateStatus", arg0) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// UpdateStatus indicates an expected call of UpdateStatus. +func (mr *MockClientInterfaceMockRecorder[T, TList]) UpdateStatus(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateStatus", reflect.TypeOf((*MockClientInterface[T, TList])(nil).UpdateStatus), arg0) +} + +// Watch mocks base method. +func (m *MockClientInterface[T, TList]) Watch(namespace string, opts v1.ListOptions) (watch.Interface, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Watch", namespace, opts) + ret0, _ := ret[0].(watch.Interface) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Watch indicates an expected call of Watch. +func (mr *MockClientInterfaceMockRecorder[T, TList]) Watch(namespace, opts interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Watch", reflect.TypeOf((*MockClientInterface[T, TList])(nil).Watch), namespace, opts) +} + +// MockNonNamespacedClientInterface is a mock of NonNamespacedClientInterface interface. +type MockNonNamespacedClientInterface[T runtime.Object, TList runtime.Object] struct { + ctrl *gomock.Controller + recorder *MockNonNamespacedClientInterfaceMockRecorder[T, TList] +} + +// MockNonNamespacedClientInterfaceMockRecorder is the mock recorder for MockNonNamespacedClientInterface. +type MockNonNamespacedClientInterfaceMockRecorder[T runtime.Object, TList runtime.Object] struct { + mock *MockNonNamespacedClientInterface[T, TList] +} + +// NewMockNonNamespacedClientInterface creates a new mock instance. +func NewMockNonNamespacedClientInterface[T runtime.Object, TList runtime.Object](ctrl *gomock.Controller) *MockNonNamespacedClientInterface[T, TList] { + mock := &MockNonNamespacedClientInterface[T, TList]{ctrl: ctrl} + mock.recorder = &MockNonNamespacedClientInterfaceMockRecorder[T, TList]{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockNonNamespacedClientInterface[T, TList]) EXPECT() *MockNonNamespacedClientInterfaceMockRecorder[T, TList] { + return m.recorder +} + +// Create mocks base method. +func (m *MockNonNamespacedClientInterface[T, TList]) Create(arg0 T) (T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Create", arg0) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Create indicates an expected call of Create. +func (mr *MockNonNamespacedClientInterfaceMockRecorder[T, TList]) Create(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Create", reflect.TypeOf((*MockNonNamespacedClientInterface[T, TList])(nil).Create), arg0) +} + +// Delete mocks base method. +func (m *MockNonNamespacedClientInterface[T, TList]) Delete(name string, options *v1.DeleteOptions) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Delete", name, options) + ret0, _ := ret[0].(error) + return ret0 +} + +// Delete indicates an expected call of Delete. +func (mr *MockNonNamespacedClientInterfaceMockRecorder[T, TList]) Delete(name, options interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Delete", reflect.TypeOf((*MockNonNamespacedClientInterface[T, TList])(nil).Delete), name, options) +} + +// Get mocks base method. +func (m *MockNonNamespacedClientInterface[T, TList]) Get(name string, options v1.GetOptions) (T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Get", name, options) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Get indicates an expected call of Get. +func (mr *MockNonNamespacedClientInterfaceMockRecorder[T, TList]) Get(name, options interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockNonNamespacedClientInterface[T, TList])(nil).Get), name, options) +} + +// List mocks base method. +func (m *MockNonNamespacedClientInterface[T, TList]) List(opts v1.ListOptions) (TList, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "List", opts) + ret0, _ := ret[0].(TList) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// List indicates an expected call of List. +func (mr *MockNonNamespacedClientInterfaceMockRecorder[T, TList]) List(opts interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockNonNamespacedClientInterface[T, TList])(nil).List), opts) +} + +// Patch mocks base method. +func (m *MockNonNamespacedClientInterface[T, TList]) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (T, error) { + m.ctrl.T.Helper() + varargs := []interface{}{name, pt, data} + for _, a := range subresources { + varargs = append(varargs, a) + } + ret := m.ctrl.Call(m, "Patch", varargs...) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Patch indicates an expected call of Patch. +func (mr *MockNonNamespacedClientInterfaceMockRecorder[T, TList]) Patch(name, pt, data interface{}, subresources ...interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + varargs := append([]interface{}{name, pt, data}, subresources...) + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Patch", reflect.TypeOf((*MockNonNamespacedClientInterface[T, TList])(nil).Patch), varargs...) +} + +// Update mocks base method. +func (m *MockNonNamespacedClientInterface[T, TList]) Update(arg0 T) (T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Update", arg0) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Update indicates an expected call of Update. +func (mr *MockNonNamespacedClientInterfaceMockRecorder[T, TList]) Update(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Update", reflect.TypeOf((*MockNonNamespacedClientInterface[T, TList])(nil).Update), arg0) +} + +// UpdateStatus mocks base method. +func (m *MockNonNamespacedClientInterface[T, TList]) UpdateStatus(arg0 T) (T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpdateStatus", arg0) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// UpdateStatus indicates an expected call of UpdateStatus. +func (mr *MockNonNamespacedClientInterfaceMockRecorder[T, TList]) UpdateStatus(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdateStatus", reflect.TypeOf((*MockNonNamespacedClientInterface[T, TList])(nil).UpdateStatus), arg0) +} + +// Watch mocks base method. +func (m *MockNonNamespacedClientInterface[T, TList]) Watch(opts v1.ListOptions) (watch.Interface, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Watch", opts) + ret0, _ := ret[0].(watch.Interface) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Watch indicates an expected call of Watch. +func (mr *MockNonNamespacedClientInterfaceMockRecorder[T, TList]) Watch(opts interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Watch", reflect.TypeOf((*MockNonNamespacedClientInterface[T, TList])(nil).Watch), opts) +} + +// MockCacheInterface is a mock of CacheInterface interface. +type MockCacheInterface[T runtime.Object] struct { + ctrl *gomock.Controller + recorder *MockCacheInterfaceMockRecorder[T] +} + +// MockCacheInterfaceMockRecorder is the mock recorder for MockCacheInterface. +type MockCacheInterfaceMockRecorder[T runtime.Object] struct { + mock *MockCacheInterface[T] +} + +// NewMockCacheInterface creates a new mock instance. +func NewMockCacheInterface[T runtime.Object](ctrl *gomock.Controller) *MockCacheInterface[T] { + mock := &MockCacheInterface[T]{ctrl: ctrl} + mock.recorder = &MockCacheInterfaceMockRecorder[T]{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockCacheInterface[T]) EXPECT() *MockCacheInterfaceMockRecorder[T] { + return m.recorder +} + +// AddIndexer mocks base method. +func (m *MockCacheInterface[T]) AddIndexer(indexName string, indexer generic.Indexer[T]) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddIndexer", indexName, indexer) +} + +// AddIndexer indicates an expected call of AddIndexer. +func (mr *MockCacheInterfaceMockRecorder[T]) AddIndexer(indexName, indexer interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddIndexer", reflect.TypeOf((*MockCacheInterface[T])(nil).AddIndexer), indexName, indexer) +} + +// Get mocks base method. +func (m *MockCacheInterface[T]) Get(namespace, name string) (T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Get", namespace, name) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Get indicates an expected call of Get. +func (mr *MockCacheInterfaceMockRecorder[T]) Get(namespace, name interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockCacheInterface[T])(nil).Get), namespace, name) +} + +// GetByIndex mocks base method. +func (m *MockCacheInterface[T]) GetByIndex(indexName, key string) ([]T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetByIndex", indexName, key) + ret0, _ := ret[0].([]T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetByIndex indicates an expected call of GetByIndex. +func (mr *MockCacheInterfaceMockRecorder[T]) GetByIndex(indexName, key interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByIndex", reflect.TypeOf((*MockCacheInterface[T])(nil).GetByIndex), indexName, key) +} + +// List mocks base method. +func (m *MockCacheInterface[T]) List(namespace string, selector labels.Selector) ([]T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "List", namespace, selector) + ret0, _ := ret[0].([]T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// List indicates an expected call of List. +func (mr *MockCacheInterfaceMockRecorder[T]) List(namespace, selector interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockCacheInterface[T])(nil).List), namespace, selector) +} + +// MockNonNamespacedCacheInterface is a mock of NonNamespacedCacheInterface interface. +type MockNonNamespacedCacheInterface[T runtime.Object] struct { + ctrl *gomock.Controller + recorder *MockNonNamespacedCacheInterfaceMockRecorder[T] +} + +// MockNonNamespacedCacheInterfaceMockRecorder is the mock recorder for MockNonNamespacedCacheInterface. +type MockNonNamespacedCacheInterfaceMockRecorder[T runtime.Object] struct { + mock *MockNonNamespacedCacheInterface[T] +} + +// NewMockNonNamespacedCacheInterface creates a new mock instance. +func NewMockNonNamespacedCacheInterface[T runtime.Object](ctrl *gomock.Controller) *MockNonNamespacedCacheInterface[T] { + mock := &MockNonNamespacedCacheInterface[T]{ctrl: ctrl} + mock.recorder = &MockNonNamespacedCacheInterfaceMockRecorder[T]{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockNonNamespacedCacheInterface[T]) EXPECT() *MockNonNamespacedCacheInterfaceMockRecorder[T] { + return m.recorder +} + +// AddIndexer mocks base method. +func (m *MockNonNamespacedCacheInterface[T]) AddIndexer(indexName string, indexer generic.Indexer[T]) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "AddIndexer", indexName, indexer) +} + +// AddIndexer indicates an expected call of AddIndexer. +func (mr *MockNonNamespacedCacheInterfaceMockRecorder[T]) AddIndexer(indexName, indexer interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddIndexer", reflect.TypeOf((*MockNonNamespacedCacheInterface[T])(nil).AddIndexer), indexName, indexer) +} + +// Get mocks base method. +func (m *MockNonNamespacedCacheInterface[T]) Get(name string) (T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Get", name) + ret0, _ := ret[0].(T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Get indicates an expected call of Get. +func (mr *MockNonNamespacedCacheInterfaceMockRecorder[T]) Get(name interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Get", reflect.TypeOf((*MockNonNamespacedCacheInterface[T])(nil).Get), name) +} + +// GetByIndex mocks base method. +func (m *MockNonNamespacedCacheInterface[T]) GetByIndex(indexName, key string) ([]T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetByIndex", indexName, key) + ret0, _ := ret[0].([]T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetByIndex indicates an expected call of GetByIndex. +func (mr *MockNonNamespacedCacheInterfaceMockRecorder[T]) GetByIndex(indexName, key interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetByIndex", reflect.TypeOf((*MockNonNamespacedCacheInterface[T])(nil).GetByIndex), indexName, key) +} + +// List mocks base method. +func (m *MockNonNamespacedCacheInterface[T]) List(selector labels.Selector) ([]T, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "List", selector) + ret0, _ := ret[0].([]T) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// List indicates an expected call of List. +func (mr *MockNonNamespacedCacheInterfaceMockRecorder[T]) List(selector interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockNonNamespacedCacheInterface[T])(nil).List), selector) +}