Last active
February 14, 2019 20:50
-
-
Save gerred/284cd176ded21fe5a2c263792d27b849 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package dynamic | |
import ( | |
"fmt" | |
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" | |
"sigs.k8s.io/controller-runtime/pkg/client/config" | |
"sigs.k8s.io/controller-runtime/pkg/controller" | |
"sigs.k8s.io/controller-runtime/pkg/handler" | |
"sigs.k8s.io/controller-runtime/pkg/manager" | |
"sigs.k8s.io/controller-runtime/pkg/reconcile" | |
"sigs.k8s.io/controller-runtime/pkg/source" | |
"sync" | |
"time" | |
) | |
type ControllerRegistry struct { | |
controllers map[string](chan struct{}) | |
errChan chan error | |
sync.Mutex | |
mgr manager.Manager | |
} | |
func (c *ControllerRegistry) Register(u unstructured.Unstructured) error { | |
c.Lock() | |
defer c.Unlock() | |
if c.controllers == nil { | |
c.controllers = map[string](chan struct{}){} | |
} | |
cfg, err := config.GetConfig() | |
if err != nil { | |
return err | |
} | |
stopMgr := make(chan struct{}) | |
if c.mgr == nil { | |
mgr, err := manager.New(cfg, manager.Options{}) | |
c.mgr = mgr | |
if err != nil { | |
return err | |
} | |
go c.mgr.Start(stopMgr) | |
} | |
ctrlName := fmt.Sprintf("%s-%s-%d", u.GroupVersionKind().String(), "controller", time.Now().Unix()) | |
ctrl, err := controller.New(ctrlName, c.mgr, controller.Options{ | |
Reconciler: reconcile.Func(func(o reconcile.Request) (reconcile.Result, error) { | |
fmt.Println("RECONCILING DYNAMIC THING") | |
return reconcile.Result{}, nil | |
}), | |
}) | |
if err := ctrl.Watch(&source.Kind{Type: &u}, &handler.EnqueueRequestForObject{}); err != nil { | |
fmt.Printf("%+v\n", err) | |
} | |
ctrlCh := make(chan struct{}) | |
c.controllers[u.GroupVersionKind().String()] = ctrlCh | |
return nil | |
} | |
func (c *ControllerRegistry) Stop(u unstructured.Unstructured) error { | |
c.Lock() | |
gvk := u.GroupVersionKind().String() | |
close(c.controllers[gvk]) | |
delete(c.controllers, gvk) | |
c.Unlock() | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment