Skip to content

Commit

Permalink
chore: Make managed-by label value transparent (#1894)
Browse files Browse the repository at this point in the history
* Change managedBy label to kyma instead of lifecycle-manager or declarative-v2

* test change

* Revert test change

* Add managed by label to skr-webhook resources and kyma cr

* Add managed by label to default CR

* Add managed by label to CRDs and moduletemplate crds

* fix linting issues

* fix coverage

* Rename kymalabelvalue variable

* Add label to default CR

* Add label to resources

* Add a helper function for the merging of maps

* Fix linting issues

---------

Co-authored-by: Christoph Schwägerl <[email protected]>
  • Loading branch information
nesmabadr and c-pius authored Oct 1, 2024
1 parent 0370267 commit 7f8e043
Show file tree
Hide file tree
Showing 19 changed files with 194 additions and 68 deletions.
6 changes: 4 additions & 2 deletions api/shared/operator_labels.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ const (
ControllerName = OperatorGroup + Separator + "controller-name"
ChannelLabel = OperatorGroup + Separator + "channel"
// ManagedBy defines the controller managing the resource.
ManagedBy = OperatorGroup + Separator + "managed-by"
ManagedBy = OperatorGroup + Separator + "managed-by"
ManagedByLabelValue = kymaValue
kymaValue = "kyma"

IstioInjectionLabel = "istio-injection"
WardenLabel = "namespaces.warden.kyma-project.io/validate"
Expand All @@ -24,7 +26,7 @@ const (
// WatchedByLabel defines a redirect to a controller that should be getting a notification
// if this resource is changed.
WatchedByLabel = OperatorGroup + Separator + "watched-by"
WatchedByLabelValue = "kyma"
WatchedByLabelValue = kymaValue
// PurposeLabel defines the purpose of the resource, i.e. Secrets which will be used to certificate management.
PurposeLabel = OperatorGroup + Separator + "purpose"
CertManager = "klm-watcher-cert-manager"
Expand Down
6 changes: 3 additions & 3 deletions api/v1beta2/kyma_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,9 @@ type Module struct {
// ModuleTemplate based on this specific version.
// The Version and Channel are mutually exclusive options.
// The regular expression come from here: https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
// json:"-" to disable installation of specific versions until decided to roll this out
// see https://github.com/kyma-project/lifecycle-manager/issues/1847
Version string `json:"-"`
// json:"-" to disable installation of specific versions until decided to roll this out
// see https://github.com/kyma-project/lifecycle-manager/issues/1847
Version string `json:"-"`

// RemoteModuleTemplateRef is deprecated and will no longer have any functionality.
// It will be removed in the upcoming API version.
Expand Down
1 change: 0 additions & 1 deletion api/v1beta2/moduletemplate_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,6 @@ func (m *ModuleTemplate) GetVersion() (*semver.Version, error) {
}
} else {
versionValue = m.Spec.Version

}

version, err := semver.NewVersion(versionValue)
Expand Down
4 changes: 2 additions & 2 deletions internal/controller/manifest/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ import (
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/source"

"github.com/kyma-project/lifecycle-manager/api/shared"
"github.com/kyma-project/lifecycle-manager/api/v1beta2"
declarativev2 "github.com/kyma-project/lifecycle-manager/internal/declarative/v2"
"github.com/kyma-project/lifecycle-manager/internal/pkg/metrics"
"github.com/kyma-project/lifecycle-manager/pkg/queue"
"github.com/kyma-project/lifecycle-manager/pkg/security"
Expand Down Expand Up @@ -52,7 +52,7 @@ func SetupWithManager(mgr manager.Manager,
}

runnableListener := watcherevent.NewSKREventListener(
settings.ListenerAddr, strings.ToLower(declarativev2.OperatorName),
settings.ListenerAddr, strings.ToLower(shared.OperatorName),
verifyFunc,
)

Expand Down
49 changes: 14 additions & 35 deletions internal/declarative/v2/default_transforms.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,10 @@ import (
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"

"github.com/kyma-project/lifecycle-manager/api/shared"
"github.com/kyma-project/lifecycle-manager/internal/util/collections"
)

const (
OperatorName = "module-manager"
ManagedByLabelValue = "declarative-v2"
DisclaimerAnnotation = shared.OperatorGroup + shared.Separator + "managed-by-reconciler-disclaimer"
DisclaimerAnnotationValue = "DO NOT EDIT - This resource is managed by Kyma.\n" +
"Any modifications are discarded and the resource is reverted to the original state."
Expand All @@ -32,44 +31,24 @@ func DisclaimerTransform(_ context.Context, _ Object, resources []*unstructured.

func KymaComponentTransform(_ context.Context, obj Object, resources []*unstructured.Unstructured) error {
for _, resource := range resources {
lbls := resource.GetLabels()
if lbls == nil {
lbls = make(map[string]string)
}
lbls["app.kubernetes.io/component"] = obj.GetName()
lbls["app.kubernetes.io/part-of"] = "Kyma"
resource.SetLabels(lbls)
}
return nil
}

func ManagedByDeclarativeV2(_ context.Context, _ Object, resources []*unstructured.Unstructured) error {
for _, resource := range resources {
lbls := resource.GetLabels()
if lbls == nil {
lbls = make(map[string]string)
}
// legacy managed by value
lbls[shared.ManagedBy] = ManagedByLabelValue
resource.SetLabels(lbls)
resource.SetLabels(collections.MergeMaps(resource.GetLabels(), map[string]string{
"app.kubernetes.io/component": obj.GetName(),
"app.kubernetes.io/part-of": "Kyma",
}))
}
return nil
}

func watchedByOwnedBy(_ context.Context, obj Object, resources []*unstructured.Unstructured) error {
func WatchedByManagedByOwnedBy(_ context.Context, obj Object, resources []*unstructured.Unstructured) error {
for _, resource := range resources {
lbls := resource.GetLabels()
if lbls == nil {
lbls = make(map[string]string)
}
lbls[shared.WatchedByLabel] = shared.WatchedByLabelValue

annotations := resource.GetAnnotations()
if annotations == nil {
annotations = make(map[string]string)
}
annotations[shared.OwnedByAnnotation] = fmt.Sprintf(OwnedByFormat, obj.GetNamespace(), obj.GetName())
resource.SetLabels(lbls)
resource.SetLabels(collections.MergeMaps(resource.GetLabels(), map[string]string{
shared.WatchedByLabel: shared.WatchedByLabelValue,
shared.ManagedBy: shared.ManagedByLabelValue,
}))

resource.SetAnnotations(collections.MergeMaps(resource.GetAnnotations(), map[string]string{
shared.OwnedByAnnotation: fmt.Sprintf(OwnedByFormat, obj.GetNamespace(), obj.GetName()),
}))
}
return nil
}
15 changes: 10 additions & 5 deletions internal/declarative/v2/default_transforms_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,8 @@ func Test_defaultTransforms(t *testing.T) {
},
},
{
"empty ManagedByDeclarativeV2",
declarativev2.ManagedByDeclarativeV2,
"empty WatchedByManagedByOwnedBy",
declarativev2.WatchedByManagedByOwnedBy,
[]*unstructured.Unstructured{},
func(testingT assert.TestingT, err error, i ...interface{}) bool {
require.NoError(t, err)
Expand Down Expand Up @@ -87,8 +87,8 @@ func Test_defaultTransforms(t *testing.T) {
},
},
{
"simple ManagedByDeclarativeV2",
declarativev2.ManagedByDeclarativeV2,
"simple WatchedByManagedByOwnedBy",
declarativev2.WatchedByManagedByOwnedBy,
[]*unstructured.Unstructured{{Object: map[string]any{}}},
func(testingT assert.TestingT, err error, i ...interface{}) bool {
require.NoError(t, err)
Expand All @@ -97,9 +97,14 @@ func Test_defaultTransforms(t *testing.T) {
unstruct := unstructs[0]
assert.NotEmpty(testingT, unstruct)
assert.NotNil(testingT, unstruct.GetLabels())
assert.NotNil(testingT, unstruct.GetAnnotations())
assert.Contains(testingT, unstruct.GetLabels(), shared.ManagedBy)
assert.Equal(testingT, declarativev2.ManagedByLabelValue,
assert.Contains(testingT, unstruct.GetLabels(), shared.WatchedByLabel)
assert.Contains(testingT, unstruct.GetAnnotations(), shared.OwnedByAnnotation)
assert.Equal(testingT, shared.ManagedByLabelValue,
unstruct.GetLabels()[shared.ManagedBy])
assert.Equal(testingT, shared.WatchedByLabelValue,
unstruct.GetLabels()[shared.WatchedByLabel])
return true
},
},
Expand Down
8 changes: 6 additions & 2 deletions internal/declarative/v2/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (
"k8s.io/client-go/tools/record"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"

"github.com/kyma-project/lifecycle-manager/api/shared"
)

const (
Expand All @@ -21,14 +23,16 @@ const (
func DefaultOptions() *Options {
return (&Options{}).Apply(
WithPostRenderTransform(
ManagedByDeclarativeV2,
watchedByOwnedBy,
WatchedByManagedByOwnedBy,
KymaComponentTransform,
DisclaimerTransform,
),
WithSingletonClientCache(NewMemoryClientCache()),
WithManifestCache(os.TempDir()),
WithManifestParser(NewInMemoryCachedManifestParser(DefaultInMemoryParseTTL)),
WithCustomResourceLabels{
shared.ManagedBy: shared.ManagedByLabelValue,
},
)
}

Expand Down
10 changes: 9 additions & 1 deletion internal/manifest/custom_resource.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@ import (
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"

"github.com/kyma-project/lifecycle-manager/api/shared"
"github.com/kyma-project/lifecycle-manager/api/v1beta2"
declarativev2 "github.com/kyma-project/lifecycle-manager/internal/declarative/v2"
"github.com/kyma-project/lifecycle-manager/internal/util/collections"
"github.com/kyma-project/lifecycle-manager/pkg/util"
)

Expand All @@ -31,6 +33,10 @@ func PostRunCreateCR(
}

resource := manifest.Spec.Resource.DeepCopy()
resource.SetLabels(collections.MergeMaps(resource.GetLabels(), map[string]string{
shared.ManagedBy: shared.ManagedByLabelValue,
}))

err := skr.Create(ctx, resource, client.FieldOwner(declarativev2.CustomResourceManagerFinalizer))
if err != nil && !apierrors.IsAlreadyExists(err) {
return fmt.Errorf("failed to create resource: %w", err)
Expand All @@ -41,9 +47,11 @@ func PostRunCreateCR(
oMeta.SetGroupVersionKind(obj.GetObjectKind().GroupVersionKind())
oMeta.SetNamespace(obj.GetNamespace())
oMeta.SetFinalizers(obj.GetFinalizers())

if added := controllerutil.AddFinalizer(oMeta, declarativev2.CustomResourceManagerFinalizer); added {
if err := kcp.Patch(
ctx, oMeta, client.Apply, client.ForceOwnership, client.FieldOwner(declarativev2.CustomResourceManagerFinalizer),
ctx, oMeta, client.Apply, client.ForceOwnership,
client.FieldOwner(declarativev2.CustomResourceManagerFinalizer),
); err != nil {
return fmt.Errorf("failed to patch resource: %w", err)
}
Expand Down
20 changes: 16 additions & 4 deletions internal/remote/crd_upgrade.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/kyma-project/lifecycle-manager/api/shared"
"github.com/kyma-project/lifecycle-manager/api/v1beta2"
"github.com/kyma-project/lifecycle-manager/internal/crd"
"github.com/kyma-project/lifecycle-manager/internal/util/collections"
)

type SyncCrdsUseCase struct {
Expand All @@ -24,7 +25,9 @@ type SyncCrdsUseCase struct {
crdCache *crd.Cache
}

func NewSyncCrdsUseCase(kcpClient client.Client, skrContextFactory SkrContextProvider, cache *crd.Cache) SyncCrdsUseCase {
func NewSyncCrdsUseCase(kcpClient client.Client, skrContextFactory SkrContextProvider,
cache *crd.Cache,
) SyncCrdsUseCase {
if cache == nil {
return SyncCrdsUseCase{
kcpClient: kcpClient,
Expand Down Expand Up @@ -52,7 +55,8 @@ func (s *SyncCrdsUseCase) Execute(ctx context.Context, kyma *v1beta2.Kyma) (bool
}
}

moduleTemplateCrdUpdated, err := s.fetchCrdsAndUpdateKymaAnnotations(ctx, skrContext.Client, kyma, shared.ModuleTemplateKind.Plural())
moduleTemplateCrdUpdated, err := s.fetchCrdsAndUpdateKymaAnnotations(ctx, skrContext.Client, kyma,
shared.ModuleTemplateKind.Plural())
if err != nil {
err = client.IgnoreNotFound(err)
if err != nil {
Expand All @@ -70,6 +74,11 @@ func PatchCRD(ctx context.Context, clnt client.Client, crd *apiextensionsv1.Cust
crdToApply.Spec = crd.Spec
crdToApply.Spec.Conversion.Strategy = apiextensionsv1.NoneConverter
crdToApply.Spec.Conversion.Webhook = nil

crdToApply.SetLabels(collections.MergeMaps(crdToApply.GetLabels(), map[string]string{
shared.ManagedBy: shared.ManagedByLabelValue,
}))

err := clnt.Patch(ctx, crdToApply,
client.Apply,
client.ForceOwnership,
Expand Down Expand Up @@ -127,7 +136,8 @@ func getAnnotation(crd *apiextensionsv1.CustomResourceDefinition, crdType CrdTyp
return fmt.Sprintf("%s-%s-crd-generation", strings.ToLower(crd.Spec.Names.Kind), strings.ToLower(string(crdType)))
}

func (s *SyncCrdsUseCase) fetchCrdsAndUpdateKymaAnnotations(ctx context.Context, skrClient Client, kyma *v1beta2.Kyma, plural string,
func (s *SyncCrdsUseCase) fetchCrdsAndUpdateKymaAnnotations(ctx context.Context, skrClient Client, kyma *v1beta2.Kyma,
plural string,
) (bool, error) {
kcpCrd, skrCrd, err := s.fetchCrds(ctx, skrClient, plural)
if err != nil {
Expand All @@ -153,7 +163,9 @@ func (s *SyncCrdsUseCase) fetchCrdsAndUpdateKymaAnnotations(ctx context.Context,
return crdUpdated, nil
}

func (s *SyncCrdsUseCase) fetchCrds(ctx context.Context, skrClient Client, plural string) (*apiextensionsv1.CustomResourceDefinition, *apiextensionsv1.CustomResourceDefinition, error) {
func (s *SyncCrdsUseCase) fetchCrds(ctx context.Context, skrClient Client,
plural string,
) (*apiextensionsv1.CustomResourceDefinition, *apiextensionsv1.CustomResourceDefinition, error) {
kcpCrdName := fmt.Sprintf("%s.%s", plural, v1beta2.GroupVersion.Group)
kcpCrd, ok := s.crdCache.Get(kcpCrdName)
if !ok {
Expand Down
12 changes: 10 additions & 2 deletions internal/remote/remote_catalog.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (

"github.com/kyma-project/lifecycle-manager/api/shared"
"github.com/kyma-project/lifecycle-manager/api/v1beta2"
"github.com/kyma-project/lifecycle-manager/internal/util/collections"
"github.com/kyma-project/lifecycle-manager/pkg/util"
)

Expand All @@ -37,7 +38,9 @@ type Catalog interface {
Delete(ctx context.Context) error
}

func NewRemoteCatalogFromKyma(kcpClient client.Client, skrContextFactory SkrContextProvider, remoteSyncNamespace string) *RemoteCatalog {
func NewRemoteCatalogFromKyma(kcpClient client.Client, skrContextFactory SkrContextProvider,
remoteSyncNamespace string,
) *RemoteCatalog {
force := true
return NewRemoteCatalog(kcpClient, skrContextFactory,
Settings{
Expand Down Expand Up @@ -212,6 +215,9 @@ func (c *RemoteCatalog) prepareForSSA(moduleTemplate *v1beta2.ModuleTemplate) {
moduleTemplate.SetResourceVersion("")
moduleTemplate.SetUID("")
moduleTemplate.SetManagedFields([]apimetav1.ManagedFieldsEntry{})
moduleTemplate.SetLabels(collections.MergeMaps(moduleTemplate.GetLabels(), map[string]string{
shared.ManagedBy: shared.ManagedByLabelValue,
}))

if c.settings.Namespace != "" {
moduleTemplate.SetNamespace(c.settings.Namespace)
Expand Down Expand Up @@ -250,7 +256,9 @@ func (c *RemoteCatalog) Delete(
func (c *RemoteCatalog) createModuleTemplateCRDInRuntime(ctx context.Context, kyma types.NamespacedName) error {
kcpCrd := &apiextensionsv1.CustomResourceDefinition{}
skrCrd := &apiextensionsv1.CustomResourceDefinition{}
objKey := client.ObjectKey{Name: fmt.Sprintf("%s.%s", shared.ModuleTemplateKind.Plural(), v1beta2.GroupVersion.Group)}
objKey := client.ObjectKey{
Name: fmt.Sprintf("%s.%s", shared.ModuleTemplateKind.Plural(), v1beta2.GroupVersion.Group),
}
err := c.kcpClient.Get(ctx, objKey, kcpCrd)
if err != nil {
return fmt.Errorf("failed to get ModuleTemplate CRD from KCP: %w", err)
Expand Down
3 changes: 2 additions & 1 deletion internal/remote/skr_context.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func (s *SkrContext) CreateKymaNamespace(ctx context.Context) error {
ObjectMeta: apimetav1.ObjectMeta{
Name: shared.DefaultRemoteNamespace,
Labels: map[string]string{
shared.ManagedBy: shared.OperatorName,
shared.ManagedBy: shared.ManagedByLabelValue,
shared.IstioInjectionLabel: shared.EnabledValue,
shared.WardenLabel: shared.EnabledValue,
},
Expand Down Expand Up @@ -210,6 +210,7 @@ func (s *SkrContext) syncWatcherLabelsAnnotations(controlPlaneKyma, remoteKyma *
}

remoteKyma.Labels[shared.WatchedByLabel] = shared.WatchedByLabelValue
remoteKyma.Labels[shared.ManagedBy] = shared.ManagedByLabelValue

if remoteKyma.Annotations == nil {
remoteKyma.Annotations = make(map[string]string)
Expand Down
15 changes: 15 additions & 0 deletions internal/util/collections/collections.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package collections

func MergeMaps(map1, map2 map[string]string) map[string]string {
mergedMap := make(map[string]string)

for k, v := range map1 {
mergedMap[k] = v
}

for k, v := range map2 {
mergedMap[k] = v
}

return mergedMap
}
Loading

0 comments on commit 7f8e043

Please sign in to comment.