/* Copyright 2021 The kcp Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package workspace import ( "context" "fmt" "sync" "time" "k8s.io/apimachinery/pkg/api/errors" utilerrors "k8s.io/apimachinery/pkg/util/errors" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/rest" "k8s.io/client-go/tools/cache" "k8s.io/client-go/util/workqueue" "k8s.io/klog/v2" kcpcache "github.com/kcp-dev/apimachinery/v2/pkg/cache" "github.com/kcp-dev/client-go/kubernetes" tenancyv1alpha1 "github.com/kcp-dev/sdk/apis/tenancy/v1alpha1" kcpclientset "github.com/kcp-dev/sdk/client/clientset/versioned/cluster" tenancyv1alpha1client "github.com/kcp-dev/sdk/client/clientset/versioned/typed/tenancy/v1alpha1" corev1alpha1informers "github.com/kcp-dev/sdk/client/informers/externalversions/core/v1alpha1" tenancyv1alpha1informers "github.com/kcp-dev/sdk/client/informers/externalversions/tenancy/v1alpha1" corev1alpha1listers "github.com/kcp-dev/sdk/client/listers/core/v1alpha1" tenancyv1alpha1listers "github.com/kcp-dev/sdk/client/listers/tenancy/v1alpha1" "github.com/kcp-dev/kcp/pkg/indexers" "github.com/kcp-dev/kcp/pkg/logging" "github.com/kcp-dev/kcp/pkg/reconciler/committer" "github.com/kcp-dev/kcp/pkg/reconciler/events" kcpmetrics "github.com/kcp-dev/kcp/pkg/server/metrics" ) const ( ControllerName = "kcp-workspace" ) type clientPool struct { mu sync.RWMutex kcpClients map[string]kcpclientset.ClusterInterface kubeClients map[string]kubernetes.ClusterInterface adminConfig *rest.Config } func newClientPool(adminConfig *rest.Config) *clientPool { return &clientPool{ kcpClients: make(map[string]kcpclientset.ClusterInterface), kubeClients: make(map[string]kubernetes.ClusterInterface), adminConfig: adminConfig, } } // getKcpClient returns a kcp client (i.e. a client that implements kcpclient.ClusterInterface) for the given shard. // the returned client establishes a direct connection with the shard with credentials stored in adminConfig. // clients are cached per shard to prevent connection leaks. func (p *clientPool) getKcpClient(shardName, baseURL string) (kcpclientset.ClusterInterface, error) { p.mu.RLock() if client, exists := p.kcpClients[shardName]; exists { p.mu.RUnlock() return client, nil } p.mu.RUnlock() p.mu.Lock() defer p.mu.Unlock() if client, exists := p.kcpClients[shardName]; exists { return client, nil } shardConfig := rest.CopyConfig(p.adminConfig) shardConfig.Host = baseURL client, err := kcpclientset.NewForConfig(shardConfig) if err != nil { return nil, fmt.Errorf("failed to create shard %q kcp client: %w", shardName, err) } p.kcpClients[shardName] = client return client, nil } // getKubeClient returns a kube client (i.e. a client that implements kubernetes.ClusterInterface) for the given shard. // the returned client establishes a direct connection with the shard with credentials stored in adminConfig. // clients are cached per shard to prevent connection leaks. func (p *clientPool) getKubeClient(shardName, baseURL string) (kubernetes.ClusterInterface, error) { p.mu.RLock() if client, exists := p.kubeClients[shardName]; exists { p.mu.RUnlock() return client, nil } p.mu.RUnlock() p.mu.Lock() defer p.mu.Unlock() if client, exists := p.kubeClients[shardName]; exists { return client, nil } shardConfig := rest.CopyConfig(p.adminConfig) shardConfig.Host = baseURL client, err := kubernetes.NewForConfig(shardConfig) if err != nil { return nil, fmt.Errorf("failed to create shard %q kube client: %w", shardName, err) } p.kubeClients[shardName] = client return client, nil } func NewController( shardName string, kcpClusterClient kcpclientset.ClusterInterface, kubeClusterClient kubernetes.ClusterInterface, logicalClusterAdminConfig *rest.Config, externalLogicalClusterAdminConfig *rest.Config, workspaceInformer tenancyv1alpha1informers.WorkspaceClusterInformer, globalShardInformer corev1alpha1informers.ShardClusterInformer, globalWorkspaceTypeInformer tenancyv1alpha1informers.WorkspaceTypeClusterInformer, logicalClusterInformer corev1alpha1informers.LogicalClusterClusterInformer, cacheLogicalClusterInformer corev1alpha1informers.LogicalClusterClusterInformer, ) (*Controller, error) { c := &Controller{ queue: workqueue.NewTypedRateLimitingQueueWithConfig( workqueue.DefaultTypedControllerRateLimiter[string](), workqueue.TypedRateLimitingQueueConfig[string]{ Name: ControllerName, }, ), shardName: shardName, logicalClusterAdminConfig: logicalClusterAdminConfig, externalLogicalClusterAdminConfig: externalLogicalClusterAdminConfig, kcpClusterClient: kcpClusterClient, kubeClusterClient: kubeClusterClient, workspaceIndexer: workspaceInformer.Informer().GetIndexer(), workspaceLister: workspaceInformer.Lister(), globalShardLister: globalShardInformer.Lister(), globalWorkspaceTypeIndexer: globalWorkspaceTypeInformer.Informer().GetIndexer(), globalWorkspaceTypeLister: globalWorkspaceTypeInformer.Lister(), logicalClusterIndexer: logicalClusterInformer.Informer().GetIndexer(), logicalClusterLister: logicalClusterInformer.Lister(), clientPool: newClientPool(logicalClusterAdminConfig), commit: committer.NewCommitter[*tenancyv1alpha1.Workspace, tenancyv1alpha1client.WorkspaceInterface, *tenancyv1alpha1.WorkspaceSpec, *tenancyv1alpha1.WorkspaceStatus](kcpClusterClient.TenancyV1alpha1().Workspaces()), countedWorkspaces: make(map[string]string), } _, _ = workspaceInformer.Informer().AddEventHandler(cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { c.enqueue(obj) c.handleMetricsOnAdd(obj) }, UpdateFunc: func(oldObj, newObj interface{}) { c.enqueue(newObj) c.handleMetricsOnUpdate(oldObj, newObj) }, DeleteFunc: func(obj interface{}) { c.enqueue(obj) c.handleMetricsOnDelete(obj) }, }) _, _ = globalShardInformer.Informer().AddEventHandler(events.WithoutSyncs(cache.ResourceEventHandlerFuncs{ AddFunc: func(obj interface{}) { c.enqueueShard(obj) }, UpdateFunc: func(obj, _ interface{}) { c.enqueueShard(obj) }, DeleteFunc: func(obj interface{}) { c.enqueueShard(obj) }, })) // Watch LogicalCluster deletions/updates so the owning Workspace is // enqueued immediately, instead of waiting for the phase reconciler's // backoff-based requeue (up to 5 min) to poll the LogicalCluster state. // Handlers are attached to both the local and the cache (replicated) // informers: the local one reacts without any replication lag when the // Workspace and its LogicalCluster live on the same shard, while the // cache one covers the cross-shard case where the LogicalCluster is // only visible via replication. _, _ = logicalClusterInformer.Informer().AddEventHandler(events.WithoutSyncs(cache.ResourceEventHandlerFuncs{ UpdateFunc: func(_, obj interface{}) { c.enqueueLogicalCluster(obj) }, DeleteFunc: func(obj interface{}) { c.enqueueLogicalCluster(obj) }, })) _, _ = cacheLogicalClusterInformer.Informer().AddEventHandler(events.WithoutSyncs(cache.ResourceEventHandlerFuncs{ UpdateFunc: func(_, obj interface{}) { c.enqueueLogicalCluster(obj) }, DeleteFunc: func(obj interface{}) { c.enqueueLogicalCluster(obj) }, })) return c, nil } type workspaceResource = committer.Resource[*tenancyv1alpha1.WorkspaceSpec, *tenancyv1alpha1.WorkspaceStatus] // Controller watches Workspaces and WorkspaceShards in order to make sure every Workspace // is scheduled to a valid Shard. type Controller struct { queue workqueue.TypedRateLimitingInterface[string] shardName string logicalClusterAdminConfig *rest.Config // for direct shard connections used during scheduling externalLogicalClusterAdminConfig *rest.Config // for front-proxy connections used during initialization kcpClusterClient kcpclientset.ClusterInterface kubeClusterClient kubernetes.ClusterInterface kcpExternalClient kcpclientset.ClusterInterface workspaceIndexer cache.Indexer workspaceLister tenancyv1alpha1listers.WorkspaceClusterLister globalShardLister corev1alpha1listers.ShardClusterLister globalWorkspaceTypeIndexer cache.Indexer globalWorkspaceTypeLister tenancyv1alpha1listers.WorkspaceTypeClusterLister logicalClusterIndexer cache.Indexer logicalClusterLister corev1alpha1listers.LogicalClusterClusterLister // clientPool manages reusable clients to prevent connection leaks clientPool *clientPool // commit creates a patch and submits it, if needed. commit func(ctx context.Context, old, new *workspaceResource) error mu sync.Mutex countedWorkspaces map[string]string } func (c *Controller) enqueue(obj interface{}) { key, err := kcpcache.MetaClusterNamespaceKeyFunc(obj) if err != nil { utilruntime.HandleError(err) return } logger := logging.WithQueueKey(logging.WithReconciler(klog.Background(), ControllerName), key) logger.V(4).Info("queueing Workspace") c.queue.Add(key) } // enqueueLogicalCluster enqueues the Workspace (if any) whose spec.cluster // matches the LogicalCluster's logical cluster name. Used to react promptly to // LogicalCluster deletions so the Workspace does not linger waiting for the // phase reconciler's polling interval. func (c *Controller) enqueueLogicalCluster(obj interface{}) { logger := logging.WithReconciler(klog.Background(), ControllerName) key, err := kcpcache.DeletionHandlingMetaClusterNamespaceKeyFunc(obj) if err != nil { utilruntime.HandleError(err) return } clusterName, _, _, err := kcpcache.SplitMetaClusterNamespaceKey(key) if err != nil { utilruntime.HandleError(err) return } workspaces, err := c.workspaceIndexer.ByIndex(byLogicalCluster, clusterName.String()) if err != nil { utilruntime.HandleError(err) return } for _, workspace := range workspaces { wsKey, err := kcpcache.MetaClusterNamespaceKeyFunc(workspace) if err != nil { utilruntime.HandleError(err) continue } logging.WithQueueKey(logger, wsKey).V(3).Info("queueing Workspace because of LogicalCluster event", "logicalCluster", clusterName) c.queue.Add(wsKey) } } func (c *Controller) enqueueShard(obj interface{}) { logger := logging.WithReconciler(klog.Background(), ControllerName) key, err := kcpcache.DeletionHandlingMetaClusterNamespaceKeyFunc(obj) if err != nil { utilruntime.HandleError(err) return } clusterName, _, name, err := kcpcache.SplitMetaClusterNamespaceKey(key) if err != nil { utilruntime.HandleError(err) return } shard, err := c.globalShardLister.Cluster(clusterName).Get(name) if err == nil { workspaces, err := c.workspaceIndexer.ByIndex(unschedulable, "true") if err != nil { utilruntime.HandleError(err) return } for _, workspace := range workspaces { key, err := kcpcache.MetaClusterNamespaceKeyFunc(workspace) if err != nil { utilruntime.HandleError(err) return } logging.WithQueueKey(logger, key).V(3).Info("queueing unschedulable Workspace because of shard update", "shard", shard) c.queue.Add(key) } } } func (c *Controller) Start(ctx context.Context, numThreads int) { defer utilruntime.HandleCrash() defer c.queue.ShutDown() // create external client that goes through the front-proxy externalConfig := rest.CopyConfig(c.externalLogicalClusterAdminConfig) kcpExternalClient, err := kcpclientset.NewForConfig(externalConfig) if err != nil { utilruntime.HandleError(err) return } c.kcpExternalClient = kcpExternalClient logger := logging.WithReconciler(klog.FromContext(ctx), ControllerName) ctx = klog.NewContext(ctx, logger) logger.Info("Starting controller") defer logger.Info("Shutting down controller") for range numThreads { go wait.Until(func() { c.startWorker(ctx) }, time.Second, ctx.Done()) } <-ctx.Done() } func (c *Controller) startWorker(ctx context.Context) { for c.processNextWorkItem(ctx) { } } func (c *Controller) processNextWorkItem(ctx context.Context) bool { // Wait until there is a new item in the working queue k, quit := c.queue.Get() if quit { return false } key := k logger := logging.WithQueueKey(klog.FromContext(ctx), key) ctx = klog.NewContext(ctx, logger) logger.V(4).Info("processing key") // No matter what, tell the queue we're done with this key, to unblock // other workers. defer c.queue.Done(key) if requeue, err := c.process(ctx, key); err != nil { utilruntime.HandleError(fmt.Errorf("%q controller failed to sync %q, err: %w", ControllerName, key, err)) c.queue.AddRateLimited(key) return true } else if requeue { // only requeue if we didn't error, but we still want to requeue c.queue.Add(key) return true } c.queue.Forget(key) return true } func (c *Controller) process(ctx context.Context, key string) (bool, error) { parent, _, name, err := kcpcache.SplitMetaClusterNamespaceKey(key) if err != nil { utilruntime.HandleError(err) return false, nil } workspace, err := c.workspaceLister.Cluster(parent).Get(name) if err != nil { if errors.IsNotFound(err) { return false, nil // object deleted before we handled it } return false, err } old := workspace workspace = workspace.DeepCopy() logger := logging.WithObject(klog.FromContext(ctx), workspace) ctx = klog.NewContext(ctx, logger) var errs []error requeue, err := c.reconcile(ctx, workspace) if err != nil { errs = append(errs, err) } // If the object being reconciled changed as a result, update it. oldResource := &workspaceResource{ObjectMeta: old.ObjectMeta, Spec: &old.Spec, Status: &old.Status} newResource := &workspaceResource{ObjectMeta: workspace.ObjectMeta, Spec: &workspace.Spec, Status: &workspace.Status} if err := c.commit(ctx, oldResource, newResource); err != nil { errs = append(errs, err) } return requeue, utilerrors.NewAggregate(errs) } // InstallIndexers adds the additional indexers that this controller requires to the informers. func InstallIndexers( workspaceInformer tenancyv1alpha1informers.WorkspaceClusterInformer, globalShardInformer corev1alpha1informers.ShardClusterInformer, globalWorkspaceTypeInformer tenancyv1alpha1informers.WorkspaceTypeClusterInformer, ) { indexers.AddIfNotPresentOrDie(workspaceInformer.Informer().GetIndexer(), cache.Indexers{ unschedulable: indexUnschedulable, byLogicalCluster: indexWorkspaceByLogicalCluster, }) indexers.AddIfNotPresentOrDie(globalWorkspaceTypeInformer.Informer().GetIndexer(), cache.Indexers{ indexers.ByLogicalClusterPathAndName: indexers.IndexByLogicalClusterPathAndName, }) } func (c *Controller) handleMetricsOnAdd(obj any) { workspace, ok := obj.(*tenancyv1alpha1.Workspace) if !ok { return } c.mu.Lock() defer c.mu.Unlock() key, err := kcpcache.MetaClusterNamespaceKeyFunc(workspace) if err != nil { return } phase := string(workspace.Status.Phase) if _, exists := c.countedWorkspaces[key]; !exists { c.countedWorkspaces[key] = phase if phase != "" { kcpmetrics.IncrementWorkspaceCount(c.shardName, phase) } } } func (c *Controller) handleMetricsOnUpdate(oldObj, newObj any) { oldWorkspace, ok := oldObj.(*tenancyv1alpha1.Workspace) if !ok { return } newWorkspace, ok := newObj.(*tenancyv1alpha1.Workspace) if !ok { return } c.mu.Lock() defer c.mu.Unlock() key, err := kcpcache.MetaClusterNamespaceKeyFunc(newWorkspace) if err != nil { return } oldPhase := string(oldWorkspace.Status.Phase) newPhase := string(newWorkspace.Status.Phase) if oldPhase != newPhase { if oldPhase != "" { kcpmetrics.DecrementWorkspaceCount(c.shardName, oldPhase) } if newPhase != "" { kcpmetrics.IncrementWorkspaceCount(c.shardName, newPhase) } c.countedWorkspaces[key] = newPhase } } func (c *Controller) handleMetricsOnDelete(obj any) { workspace, ok := obj.(*tenancyv1alpha1.Workspace) if !ok { if tombstone, ok := obj.(cache.DeletedFinalStateUnknown); ok { workspace, ok = tombstone.Obj.(*tenancyv1alpha1.Workspace) if !ok { return } } else { return } } c.mu.Lock() defer c.mu.Unlock() key, err := kcpcache.MetaClusterNamespaceKeyFunc(workspace) if err != nil { return } if phase, exists := c.countedWorkspaces[key]; exists { delete(c.countedWorkspaces, key) if phase != "" { kcpmetrics.DecrementWorkspaceCount(c.shardName, phase) } } }