~ knotless Search/
↑↓ move↵ open⇧↵ all results

johnandersen777.bsky.social/socialweb-computer-console

console.socialweb.computer: kcp, kubectl and ssh compiled to wasm in a browser tab with a terminal; a kcp fork

0
0
main
250 lines · 9.3 KB Raw History
/*
Copyright 2025 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 clustercachedresources

import (
	"context"
	"time"

	corev1 "k8s.io/api/core/v1"
	apierrors "k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/api/meta"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
	"k8s.io/apimachinery/pkg/runtime/schema"
	utilerrors "k8s.io/apimachinery/pkg/util/errors"
	"k8s.io/klog/v2"

	kcpcrypto "github.com/kcp-dev/apimachinery/v2/pkg/util/crypto"
	"github.com/kcp-dev/logicalcluster/v3"
	apisv1alpha1 "github.com/kcp-dev/sdk/apis/apis/v1alpha1"
	cachev1alpha1 "github.com/kcp-dev/sdk/apis/cache/v1alpha1"

	cacheclient "github.com/kcp-dev/kcp/pkg/cache/client"
	"github.com/kcp-dev/kcp/pkg/cache/client/shard"
	"github.com/kcp-dev/kcp/pkg/logging"
	replicationcontroller "github.com/kcp-dev/kcp/pkg/reconciler/cache/clustercachedresources/replication"
)

type reconcileStatus int

const (
	reconcileStatusStopAndRequeue reconcileStatus = iota
	reconcileStatusContinue
	reconcileStatusStop
)

type reconciler interface {
	reconcile(ctx context.Context, workspace *cachev1alpha1.ClusterCachedResource) (reconcileStatus, error)
}

// reconcile reconciles the workspace objects. It is intended to be single reconciler for all the
// workspace replated operations. For now it has single reconciler that updates the status of the
// workspace based on the mount status.
func (c *Controller) reconcile(ctx context.Context, cluster logicalcluster.Name, clusterCachedResource *cachev1alpha1.ClusterCachedResource) (bool, error) {
	reconcilers := []reconciler{
		&finalizer{},
		&validSchema{
			getResourceScope: func(gvr schema.GroupVersionResource) (meta.RESTScope, error) {
				scopedMapper := c.dynRESTMapper.ForCluster(logicalcluster.From(clusterCachedResource))
				kind, err := scopedMapper.KindFor(schema.GroupVersionResource(clusterCachedResource.Spec.GroupVersionResource))
				if err != nil {
					return nil, err
				}
				mapping, err := scopedMapper.RESTMapping(kind.GroupKind(), kind.Version)
				if err != nil {
					return nil, err
				}
				return mapping.Scope, nil
			},
		},
		&reconcileResourceMetadata{
			getKind: func(cluster logicalcluster.Name, gvr schema.GroupVersionResource) (schema.GroupVersionKind, error) {
				return c.dynRESTMapper.ForCluster(cluster).KindFor(gvr)
			},
			getRESTScope: func(cluster logicalcluster.Name, gvr schema.GroupVersionResource) (meta.RESTScope, error) {
				kind, err := c.dynRESTMapper.ForCluster(cluster).KindFor(gvr)
				if err != nil {
					return nil, err
				}
				m, err := c.dynRESTMapper.ForCluster(cluster).RESTMapping(kind.GroupKind(), kind.Version)
				if err != nil {
					return nil, err
				}
				return m.Scope, nil
			},
		},
		&identityReconciler{
			ensureSecretNamespaceExists: c.ensureSecretNamespaceExists,
			getSecret:                   c.getSecret,
			createIdentitySecret:        c.createIdentitySecret,
			secretNamespace:             c.secretNamespace,
		},
		&purge{
			deleteSelectedCacheResources: func(ctx context.Context, clusterCachedResource *cachev1alpha1.ClusterCachedResource) error {
				return c.deleteSelectedCacheResources(ctx, cluster, clusterCachedResource)
			},
		},
		&counter{
			listSelectedLocalResources: func(ctx context.Context, clusterCachedResource *cachev1alpha1.ClusterCachedResource) (*unstructured.UnstructuredList, error) {
				return c.listSelectedLocalResources(ctx, cluster, clusterCachedResource)
			},
			listSelectedClusterCachedResources: func(ctx context.Context, clusterCachedResource *cachev1alpha1.ClusterCachedResource) (*unstructured.UnstructuredList, error) {
				return c.listSelectedCacheResources(ctx, cluster, clusterCachedResource)
			},
		},
		&replication{
			shardName:                            c.shardName,
			localDynamicClusterClient:            c.localDynamicClient,
			globalDynamicClusterClient:           c.globalDynamicClient,
			kcpCacheClient:                       c.kcpCacheClient,
			dynRESTMapper:                        c.dynRESTMapper,
			localDiscoveringDynamicKcpInformers:  c.localDiscoveringDynamicKcpInformers,
			globalDiscoveringDynamicKcpInformers: c.globalDiscoveringDynamicKcpInformers,
			requeueSelf:                          c.enqueue,
			controllerRegistry:                   c.controllerRegistry,
		},
	}

	var errs []error

	requeue := false
	for _, r := range reconcilers {
		var err error
		var status reconcileStatus
		status, err = r.reconcile(ctx, clusterCachedResource)
		if err != nil {
			errs = append(errs, err)
		}
		if status == reconcileStatusStopAndRequeue {
			requeue = true
			break
		}
		if status == reconcileStatusStop {
			break
		}
	}

	return requeue, utilerrors.NewAggregate(errs)
}

func (c *Controller) listSelectedLocalResources(ctx context.Context, cluster logicalcluster.Name, clusterCachedResource *cachev1alpha1.ClusterCachedResource) (*unstructured.UnstructuredList, error) {
	gvr := schema.GroupVersionResource{
		Group:    clusterCachedResource.Spec.Group,
		Version:  clusterCachedResource.Spec.Version,
		Resource: clusterCachedResource.Spec.Resource,
	}

	selection := replicationcontroller.SelectionFor(clusterCachedResource)

	resources, err := c.localDynamicClient.Cluster(cluster.Path()).Resource(gvr).List(ctx, selection.ListOptions())
	if err != nil {
		return nil, err
	}
	// Names cannot go into the list options, so they are applied here.
	resources.Items = selection.Filter(resources.Items)

	return resources, nil
}

func (c *Controller) deleteSelectedCacheResources(ctx context.Context, cluster logicalcluster.Name, clusterCachedResource *cachev1alpha1.ClusterCachedResource) error {
	gvr := schema.GroupVersionResource{
		Group:    clusterCachedResource.Spec.Group,
		Version:  clusterCachedResource.Spec.Version,
		Resource: clusterCachedResource.Spec.Resource + ":" + clusterCachedResource.Status.IdentityHash,
	}
	if gvr.Group == "" {
		gvr.Group = "core"
	}

	ctx = cacheclient.WithShardInContext(ctx, shard.New(c.shardName))
	err := c.globalDynamicClient.Cluster(cluster.Path()).Resource(gvr).DeleteCollection(ctx, metav1.DeleteOptions{}, metav1.ListOptions{})
	return err
}

func (c *Controller) listSelectedCacheResources(ctx context.Context, cluster logicalcluster.Name, clusterCachedResource *cachev1alpha1.ClusterCachedResource) (*unstructured.UnstructuredList, error) {
	gvr := schema.GroupVersionResource{
		Group:    clusterCachedResource.Spec.Group,
		Version:  clusterCachedResource.Spec.Version,
		Resource: clusterCachedResource.Spec.Resource + ":" + clusterCachedResource.Status.IdentityHash,
	}
	if gvr.Group == "" {
		gvr.Group = "core"
	}

	ctx = cacheclient.WithShardInContext(ctx, shard.New(c.shardName))
	resources, err := c.globalDynamicClient.Cluster(cluster.Path()).Resource(gvr).List(ctx, metav1.ListOptions{})
	if err != nil {
		return nil, err
	}

	return resources, nil
}

func (c *Controller) ensureSecretNamespaceExists(ctx context.Context, clusterName logicalcluster.Name, defaultSecretNamespace string) {
	logger := klog.FromContext(ctx)
	ctx = klog.NewContext(ctx, logger)
	if _, err := c.getNamespace(clusterName, defaultSecretNamespace); apierrors.IsNotFound(err) {
		ns := &corev1.Namespace{
			ObjectMeta: metav1.ObjectMeta{
				Name:        defaultSecretNamespace,
				Annotations: map[string]string{logicalcluster.AnnotationKey: clusterName.String()},
			},
		}
		logger = logging.WithObject(logger, ns)
		if err := c.createNamespace(ctx, clusterName.Path(), ns); err != nil && !apierrors.IsAlreadyExists(err) {
			logger.Error(err, "error creating namespace for ClusterCachedResource secret identities")
			// Keep going - maybe things will work. If the secret creation fails, we'll make sure to set a condition.
		}
	}
}

func (c *Controller) createIdentitySecret(ctx context.Context, clusterName logicalcluster.Path, defaultSecretNamespace, clusterCachedResourceName string) error {
	secret, err := GenerateIdentitySecret(ctx, defaultSecretNamespace, clusterCachedResourceName)
	if err != nil {
		return err
	}
	secret.Annotations[logicalcluster.AnnotationKey] = clusterName.String()

	logger := logging.WithObject(klog.FromContext(ctx), secret)
	ctx = klog.NewContext(ctx, logger)
	logger.V(2).Info("creating identity secret")
	return c.createSecret(ctx, clusterName, secret)
}

// TODO: This is copy from apiexport controller. We should move it to a shared location.
func GenerateIdentitySecret(ctx context.Context, ns string, name string) (*corev1.Secret, error) {
	logger := klog.FromContext(ctx)
	start := time.Now()
	key := kcpcrypto.Random256BitsString()
	if dur := time.Since(start); dur > time.Millisecond*100 {
		logger.Info("identity key generation took a long time", "duration", dur)
	}

	secret := &corev1.Secret{
		ObjectMeta: metav1.ObjectMeta{
			Namespace:   ns,
			Name:        name,
			Annotations: map[string]string{},
		},
		StringData: map[string]string{
			apisv1alpha1.SecretKeyAPIExportIdentity: key,
		},
	}

	return secret, nil
}