Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: combine IsManaged & IsManagedCluster #1951

Merged
merged 2 commits into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions pkg/controllers/resources/csistoragecapacities/translator.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,6 @@ func (s *csistoragecapacitySyncer) Resource() client.Object {
return &storagev1.CSIStorageCapacity{}
}

func (s *csistoragecapacitySyncer) IsManaged(context.Context, client.Object) (bool, error) {
return true, nil
}

// TranslateMetadata translates the object's metadata
func (s *csistoragecapacitySyncer) TranslateMetadata(ctx context.Context, pObj client.Object) (client.Object, error) {
pName := mappings.CSIStorageCapacities().HostToVirtual(ctx, types.NamespacedName{Name: pObj.GetName(), Namespace: pObj.GetNamespace()}, pObj)
Expand Down
6 changes: 0 additions & 6 deletions pkg/controllers/resources/events/syncer.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package events

import (
"context"
"fmt"

synccontext "github.com/loft-sh/vcluster/pkg/controllers/syncer/context"
Expand All @@ -12,7 +11,6 @@ import (
"github.com/loft-sh/vcluster/pkg/util/translate"
corev1 "k8s.io/api/core/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/types"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
Expand Down Expand Up @@ -42,10 +40,6 @@ func (s *eventSyncer) Name() string {
return "event"
}

func (s *eventSyncer) IsManaged(ctx context.Context, pObj client.Object) (bool, error) {
return mappings.Events().HostToVirtual(ctx, types.NamespacedName{Namespace: pObj.GetNamespace(), Name: pObj.GetName()}, pObj).Name != "", nil
}

var _ syncer.Syncer = &eventSyncer{}

func (s *eventSyncer) SyncToHost(_ *synccontext.SyncContext, _ client.Object) (ctrl.Result, error) {
Expand Down
8 changes: 2 additions & 6 deletions pkg/controllers/resources/nodes/syncer.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ func modifyController(ctx *synccontext.RegisterContext, nodeServiceProvider node
}()

bld = bld.WatchesRawSource(source.Kind(ctx.PhysicalManager.GetCache(), &corev1.Pod{}, handler.TypedEnqueueRequestsFromMapFunc(func(_ context.Context, pod *corev1.Pod) []reconcile.Request {
if pod == nil || !translate.Default.IsManaged(pod) || pod.Spec.NodeName == "" {
if pod == nil || !translate.Default.IsManaged(ctx, pod) || pod.Spec.NodeName == "" {
return []reconcile.Request{}
}

Expand Down Expand Up @@ -231,7 +231,7 @@ func (s *nodeSyncer) RegisterIndices(ctx *synccontext.RegisterContext) error {
func registerIndices(ctx *synccontext.RegisterContext) error {
err := ctx.PhysicalManager.GetFieldIndexer().IndexField(ctx, &corev1.Pod{}, constants.IndexByAssigned, func(rawObj client.Object) []string {
pod := rawObj.(*corev1.Pod)
if !translate.Default.IsManaged(pod) || pod.Spec.NodeName == "" {
if !translate.Default.IsManaged(ctx, pod) || pod.Spec.NodeName == "" {
return nil
}
return []string{pod.Spec.NodeName}
Expand All @@ -249,10 +249,6 @@ func registerIndices(ctx *synccontext.RegisterContext) error {
})
}

func (s *nodeSyncer) IsManaged(_ context.Context, _ client.Object) (bool, error) {
return true, nil
}

var _ syncertypes.Syncer = &nodeSyncer{}

func (s *nodeSyncer) SyncToHost(ctx *synccontext.SyncContext, vObj client.Object) (ctrl.Result, error) {
Expand Down
2 changes: 1 addition & 1 deletion pkg/controllers/resources/nodes/translate.go
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ func (s *nodeSyncer) translateUpdateStatus(ctx *synccontext.SyncContext, pNode *
klog.Errorf("Error listing pods: %v", err)
} else {
for _, pod := range podList.Items {
if !translate.Default.IsManaged(&pod) {
if !translate.Default.IsManaged(ctx, &pod) {
// count pods that are not synced by this vcluster
nonVClusterPods++
}
Expand Down
20 changes: 6 additions & 14 deletions pkg/controllers/resources/persistentvolumes/syncer.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ func (s *persistentVolumeSyncer) SyncToVirtual(ctx *synccontext.SyncContext, pOb
sync, vPvc, err := s.shouldSync(ctx, pPersistentVolume)
if err != nil {
return ctrl.Result{}, err
} else if translate.Default.IsManagedCluster(pObj) {
} else if translate.Default.IsManaged(ctx, pObj) {
ctx.Log.Infof("delete physical persistent volume %s, because it is not needed anymore", pPersistentVolume.Name)
return syncer.DeleteHostObject(ctx, pObj, "it is not needed anymore")
} else if sync {
Expand All @@ -233,7 +233,7 @@ func (s *persistentVolumeSyncer) SyncToVirtual(ctx *synccontext.SyncContext, pOb
func (s *persistentVolumeSyncer) shouldSync(ctx context.Context, pObj *corev1.PersistentVolume) (bool, *corev1.PersistentVolumeClaim, error) {
// is there an assigned PVC?
if pObj.Spec.ClaimRef == nil {
if translate.Default.IsManagedCluster(pObj) {
if translate.Default.IsManaged(ctx, pObj) {
return true, nil, nil
}

Expand All @@ -242,31 +242,23 @@ func (s *persistentVolumeSyncer) shouldSync(ctx context.Context, pObj *corev1.Pe

vName := mappings.PersistentVolumeClaims().HostToVirtual(ctx, types.NamespacedName{Name: pObj.Spec.ClaimRef.Name, Namespace: pObj.Spec.ClaimRef.Namespace}, nil)
if vName.Name == "" {
if translate.Default.IsManagedCluster(pObj) {
if translate.Default.IsManaged(ctx, pObj) {
return true, nil, nil
}

namespace, err := translate.Default.LegacyGetTargetNamespace()
if err != nil {
return false, nil, nil
}
return pObj.Spec.ClaimRef.Namespace == namespace && pObj.Spec.PersistentVolumeReclaimPolicy == corev1.PersistentVolumeReclaimRetain, nil, nil
return translate.Default.IsTargetedNamespace(pObj.Spec.ClaimRef.Namespace) && pObj.Spec.PersistentVolumeReclaimPolicy == corev1.PersistentVolumeReclaimRetain, nil, nil
}

vPvc := &corev1.PersistentVolumeClaim{}
err := s.virtualClient.Get(ctx, vName, vPvc)
if err != nil {
if !kerrors.IsNotFound(err) {
return false, nil, err
} else if translate.Default.IsManagedCluster(pObj) {
} else if translate.Default.IsManaged(ctx, pObj) {
return true, nil, nil
}

namespace, err := translate.Default.LegacyGetTargetNamespace()
if err != nil {
return false, nil, nil
}
return pObj.Spec.ClaimRef.Namespace == namespace && pObj.Spec.PersistentVolumeReclaimPolicy == corev1.PersistentVolumeReclaimRetain, nil, nil
return translate.Default.IsTargetedNamespace(pObj.Spec.ClaimRef.Namespace) && pObj.Spec.PersistentVolumeReclaimPolicy == corev1.PersistentVolumeReclaimRetain, nil, nil
}

return true, vPvc, nil
Expand Down
2 changes: 1 addition & 1 deletion pkg/controllers/resources/persistentvolumes/translate.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ func (s *persistentVolumeSyncer) translateUpdateBackwards(ctx context.Context, v
}

// check storage class. Do not copy the name, if it was created on virtual.
if !translate.Default.IsManagedCluster(pPv) {
if !translate.Default.IsManaged(ctx, pPv) {
if !equality.Semantic.DeepEqual(vPv.Spec.StorageClassName, translatedSpec.StorageClassName) && !isStorageClassCreatedOnVirtual {
updated = translator.NewIfNil(updated, vPv)
updated.Spec.StorageClassName = translatedSpec.StorageClassName
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ func (s *volumeSnapshotContentSyncer) shouldSync(ctx context.Context, pObj *volu
if err != nil {
if !kerrors.IsNotFound(err) {
return false, nil, err
} else if translate.Default.IsManagedCluster(pObj) {
} else if translate.Default.IsManaged(ctx, pObj) {
return true, vVS, nil
}
return false, nil, nil
Expand Down
8 changes: 0 additions & 8 deletions pkg/controllers/syncer/translator/generic_translator.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,6 @@ func (n *genericTranslator) SyncToHostUpdate(ctx *context.SyncContext, vObj, pOb
return ctrl.Result{}, nil
}

func (n *genericTranslator) IsManaged(_ context2.Context, pObj client.Object) (bool, error) {
if pObj.GetNamespace() == "" {
return translate.Default.IsManagedCluster(pObj), nil
}

return translate.Default.IsManaged(pObj), nil
}

func (n *genericTranslator) TranslateMetadata(ctx context2.Context, vObj client.Object) client.Object {
pObj, err := translate.Default.SetupMetadataWithName(vObj, n.Mapper.VirtualToHost(ctx, types.NamespacedName{Name: vObj.GetName(), Namespace: vObj.GetNamespace()}, vObj))
if err != nil {
Expand Down
4 changes: 0 additions & 4 deletions pkg/controllers/syncer/translator/mirror_translator.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,3 @@ func (n *mirrorPhysicalTranslator) TranslateMetadataUpdate(_ context.Context, vO
updatedLabels := pObj.GetLabels()
return !equality.Semantic.DeepEqual(updatedAnnotations, vObj.GetAnnotations()) || !equality.Semantic.DeepEqual(updatedLabels, vObj.GetLabels()), updatedAnnotations, updatedLabels
}

func (n *mirrorPhysicalTranslator) IsManaged(context.Context, client.Object) (bool, error) {
return true, nil
}
3 changes: 2 additions & 1 deletion pkg/controllers/syncer/types/syncer.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package types

import (
synccontext "github.com/loft-sh/vcluster/pkg/controllers/syncer/context"
"github.com/loft-sh/vcluster/pkg/mappings"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
Expand All @@ -24,7 +25,7 @@ type Exporter interface {

type Syncer interface {
Object
ObjectManager
mappings.Mapper

// SyncToHost is called when a virtual object was created and needs to be synced down to the physical cluster
SyncToHost(ctx *synccontext.SyncContext, vObj client.Object) (ctrl.Result, error)
Expand Down
13 changes: 2 additions & 11 deletions pkg/controllers/syncer/types/translator.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,9 @@ import (

// Translator is used to translate names as well as metadata between virtual and physical objects
type Translator interface {
Resource() client.Object
Name() string
ObjectManager
MetadataTranslator
}

// ObjectManager is used to convert virtual to physical names and vice versa
type ObjectManager interface {
Object
mappings.Mapper

// IsManaged determines if a physical object is managed by the vcluster
IsManaged(context.Context, client.Object) (bool, error)
MetadataTranslator
}

// MetadataTranslator is used to convert metadata between virtual and physical objects and vice versa
Expand Down
4 changes: 4 additions & 0 deletions pkg/mappings/generic/mapper.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,7 @@ func (n *mapper) HostToVirtual(ctx context2.Context, req types.NamespacedName, p
Name: vObj.GetName(),
}
}

func (n *mapper) IsManaged(ctx context2.Context, pObj client.Object) (bool, error) {
return translate.Default.IsManaged(ctx, pObj), nil
}
4 changes: 4 additions & 0 deletions pkg/mappings/generic/mirror.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,7 @@ func (n *mirrorMapper) HostToVirtual(_ context.Context, req types.NamespacedName
Name: req.Name,
}
}

func (n *mirrorMapper) IsManaged(context.Context, client.Object) (bool, error) {
return true, nil
}
4 changes: 4 additions & 0 deletions pkg/mappings/resources/csistoragecapacities.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,7 @@ func (s *csiStorageCapacitiesMapper) VirtualToHost(ctx context.Context, req type
Name: pObj.GetName(),
}
}

func (s *csiStorageCapacitiesMapper) IsManaged(context.Context, client.Object) (bool, error) {
return true, nil
}
4 changes: 4 additions & 0 deletions pkg/mappings/resources/events.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ func (s *eventMapper) HostToVirtual(ctx context.Context, req types.NamespacedNam
}
}

func (s *eventMapper) IsManaged(ctx context.Context, pObj client.Object) (bool, error) {
return s.HostToVirtual(ctx, types.NamespacedName{Namespace: pObj.GetNamespace(), Name: pObj.GetName()}, pObj).Name != "", nil
}

func HostEventNameToVirtual(hostName string, hostInvolvedObjectName, virtualInvolvedObjectName string) string {
// replace name of object
if strings.HasPrefix(hostName, hostInvolvedObjectName) {
Expand Down
3 changes: 3 additions & 0 deletions pkg/mappings/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ type Mapper interface {

// HostToVirtual translates a physical name to a virtual name
HostToVirtual(ctx context.Context, req types.NamespacedName, pObj client.Object) types.NamespacedName

// IsManaged determines if a physical object is managed by the vCluster
IsManaged(context.Context, client.Object) (bool, error)
}

func Has(gvk schema.GroupVersionKind) bool {
Expand Down
41 changes: 10 additions & 31 deletions pkg/util/translate/multi_namespace.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
package translate

import (
"context"
"crypto/sha256"
"encoding/hex"
"fmt"
"regexp"
"strings"

"github.com/loft-sh/vcluster/pkg/scheme"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
Expand Down Expand Up @@ -51,42 +50,26 @@ func (s *multiNamespace) PhysicalNameClusterScoped(name string) string {
return SafeConcatName("vcluster", name, "x", s.currentNamespace, "x", VClusterName)
}

func (s *multiNamespace) IsManaged(obj runtime.Object) bool {
metaAccessor, err := meta.Accessor(obj)
if err != nil {
return false
func (s *multiNamespace) IsManaged(_ context.Context, pObj client.Object) bool {
// check if cluster scoped object
if pObj.GetNamespace() == "" {
return pObj.GetLabels()[MarkerLabel] == SafeConcatName(s.currentNamespace, "x", VClusterName)
}

// vcluster has not synced the object IF:
// If obj is not in the synced namespace OR
// If object-name annotation is not set OR
// If object-name annotation is different from actual name
if !s.IsTargetedNamespace(metaAccessor.GetNamespace()) || metaAccessor.GetAnnotations() == nil || metaAccessor.GetAnnotations()[NameAnnotation] == "" {
return false
}

_, isCM := obj.(*corev1.ConfigMap)
if isCM && metaAccessor.GetName() == "kube-root-ca.crt" {
if !s.IsTargetedNamespace(pObj.GetNamespace()) || pObj.GetAnnotations()[NameAnnotation] == "" {
return false
}

return true
}

func (s *multiNamespace) IsManagedCluster(obj runtime.Object) bool {
metaAccessor, err := meta.Accessor(obj)
if err != nil {
return false
}

if metaAccessor.GetAnnotations()[KindAnnotation] != "" {
gvk, err := apiutil.GVKForObject(obj, scheme.Scheme)
if err == nil && gvk.String() != metaAccessor.GetAnnotations()[KindAnnotation] {
} else if pObj.GetAnnotations()[KindAnnotation] != "" {
gvk, err := apiutil.GVKForObject(pObj, scheme.Scheme)
if err == nil && gvk.String() != pObj.GetAnnotations()[KindAnnotation] {
return false
}
}

return metaAccessor.GetLabels()[MarkerLabel] == SafeConcatName(s.currentNamespace, "x", VClusterName)
return true
}

func (s *multiNamespace) IsTargetedNamespace(ns string) bool {
Expand Down Expand Up @@ -177,10 +160,6 @@ func (s *multiNamespace) TranslateLabelSelectorCluster(labelSelector *metav1.Lab
return newLabelSelector
}

func (s *multiNamespace) LegacyGetTargetNamespace() (string, error) {
return "", fmt.Errorf("unsupported feature in multi-namespace mode")
}

func (s *multiNamespace) ApplyMetadata(vObj client.Object, name types.NamespacedName, syncedLabels []string, excludedAnnotations ...string) client.Object {
pObj, err := s.SetupMetadataWithName(vObj, name)
if err != nil {
Expand Down
Loading
Loading