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

chore(konnect): refactor generating object tags #675

Merged
merged 1 commit into from
Oct 1, 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
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@ package ops

import (
"fmt"
"slices"
"sort"

"github.com/samber/lo"
"sigs.k8s.io/controller-runtime/pkg/client"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"

"github.com/kong/kubernetes-configuration/pkg/metadata"
)

const (
Expand All @@ -30,30 +35,29 @@ const (
KubernetesVersionLabelKey = "k8s-version"
)

// WithKubernetesMetadataLabels returns a map of user-provided labels to be assigned to a Konnect entity with the origin
// Kubernetes object's metadata added. These can be assigned to a Konnect entitiy that supports labels (e.g. ControlPlane).
func WithKubernetesMetadataLabels(obj client.Object, userSetLabels map[string]string) map[string]string {
labels := map[string]string{
KubernetesNameLabelKey: obj.GetName(),
KubernetesUIDLabelKey: string(obj.GetUID()),
KubernetesGenerationLabelKey: fmt.Sprintf("%d", obj.GetGeneration()),
KubernetesKindLabelKey: obj.GetObjectKind().GroupVersionKind().Kind,
KubernetesGroupLabelKey: obj.GetObjectKind().GroupVersionKind().GroupVersion().Group,
KubernetesVersionLabelKey: obj.GetObjectKind().GroupVersionKind().GroupVersion().Version,
}
if k8sNamespace := obj.GetNamespace(); k8sNamespace != "" {
labels[KubernetesNamespaceLabelKey] = k8sNamespace
}
for k, v := range userSetLabels {
labels[k] = v
}
return labels
// ObjectWithMetadata is an interface that accepts an object with Kubernetes metadata and object Kind information.
type ObjectWithMetadata interface {
metav1.Object
GetObjectKind() schema.ObjectKind
}

// GenerateTagsForObject generates tags for the given object based on its Kubernetes metadata and annotations.
// An optional set of tags can be passed to be included in the generated tags (e.g. tags from the spec).
// It returns a slice of unique, sorted strings for deterministic output.
func GenerateTagsForObject(obj ObjectWithMetadata, additionalTags ...string) []string {
var (
annotationTags = metadata.ExtractTags(obj)
k8sMetaTags = generateKubernetesMetadataTags(obj)
res = lo.Uniq(slices.Concat(annotationTags, k8sMetaTags, additionalTags))
)
sort.Strings(res)
return res
}

// GenerateKubernetesMetadataTags generates a list of tags from a Kubernetes object's metadata. The tags are formatted as
// generateKubernetesMetadataTags generates a list of tags from a Kubernetes object's metadata. The tags are formatted as
// "key:value". These can be attached to a Konnect entity that doesn't support labels, but supports tags (e.g. Route, Service,
// Consumer, etc.).
func GenerateKubernetesMetadataTags(obj client.Object) []string {
func generateKubernetesMetadataTags(obj ObjectWithMetadata) []string {
// Use a list of Entry instead of a builtin map to preserve the order of the labels.
labels := []lo.Entry[string, string]{
{Key: KubernetesGenerationLabelKey, Value: fmt.Sprintf("%d", obj.GetGeneration())},
Expand All @@ -72,3 +76,23 @@ func GenerateKubernetesMetadataTags(obj client.Object) []string {
}
return tags
}

// WithKubernetesMetadataLabels returns a map of user-provided labels to be assigned to a Konnect entity with the origin
// Kubernetes object's metadata added. These can be assigned to a Konnect entity that supports labels (e.g. ControlPlane).
func WithKubernetesMetadataLabels(obj ObjectWithMetadata, userSetLabels map[string]string) map[string]string {
labels := map[string]string{
KubernetesNameLabelKey: obj.GetName(),
KubernetesUIDLabelKey: string(obj.GetUID()),
KubernetesGenerationLabelKey: fmt.Sprintf("%d", obj.GetGeneration()),
KubernetesKindLabelKey: obj.GetObjectKind().GroupVersionKind().Kind,
KubernetesGroupLabelKey: obj.GetObjectKind().GroupVersionKind().GroupVersion().Group,
KubernetesVersionLabelKey: obj.GetObjectKind().GroupVersionKind().GroupVersion().Version,
}
if k8sNamespace := obj.GetNamespace(); k8sNamespace != "" {
labels[KubernetesNamespaceLabelKey] = k8sNamespace
}
for k, v := range userSetLabels {
labels[k] = v
}
return labels
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (

"github.com/stretchr/testify/require"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"

"github.com/kong/gateway-operator/controller/konnect/ops"
)
Expand All @@ -16,10 +15,6 @@ type testObjectKind struct {
metav1.ObjectMeta
}

func (b *testObjectKind) DeepCopyObject() runtime.Object {
return b
}

func TestWithKubernetesMetadataLabels(t *testing.T) {
testCases := []struct {
name string
Expand Down Expand Up @@ -82,63 +77,116 @@ func TestWithKubernetesMetadataLabels(t *testing.T) {
}
}

func TestGenerateKubernetesMetadataTags(t *testing.T) {
func TestGenerateTagsForObject(t *testing.T) {
namespacedObject := func() testObjectKind {
return testObjectKind{
ObjectMeta: metav1.ObjectMeta{
Name: "test-object",
Namespace: "test-namespace",
UID: "test-uid",
Generation: 2,
},
TypeMeta: metav1.TypeMeta{
Kind: "TestObjectKind",
APIVersion: "test.objects.io/v1",
},
}
}
clusterScopedObject := func() testObjectKind {
return testObjectKind{
ObjectMeta: metav1.ObjectMeta{
Name: "test-object",
UID: "test-uid",
Generation: 2,
},
TypeMeta: metav1.TypeMeta{
Kind: "TestObjectKind",
APIVersion: "test.objects.io/v1",
},
}
}

testCases := []struct {
name string
obj testObjectKind
expectedTags []string
name string
obj testObjectKind
additionalTags []string
expectedTags []string
}{
{
name: "all object's expected fields are set",
obj: testObjectKind{
TypeMeta: metav1.TypeMeta{
Kind: "TestObjectKind",
APIVersion: "test.objects.io/v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "test-object",
Namespace: "test-namespace",
UID: "test-uid",
Generation: 2,
},
},
obj: namespacedObject(),
expectedTags: []string{
"k8s-generation:2",
"k8s-group:test.objects.io",
"k8s-kind:TestObjectKind",
"k8s-name:test-object",
"k8s-namespace:test-namespace",
"k8s-uid:test-uid",
"k8s-version:v1",
"k8s-namespace:test-namespace",
},
},
{
name: "namespace is not set (cluster-scoped object)",
obj: testObjectKind{
TypeMeta: metav1.TypeMeta{
Kind: "TestObjectKind",
APIVersion: "test.objects.io/v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "test-object",
UID: "test-uid",
Generation: 2,
},
obj: clusterScopedObject(),
expectedTags: []string{
"k8s-generation:2",
"k8s-group:test.objects.io",
"k8s-kind:TestObjectKind",
"k8s-name:test-object",
"k8s-uid:test-uid",
"k8s-version:v1",
},
},
{
name: "annotation tags are set",
obj: func() testObjectKind {
obj := namespacedObject()
obj.ObjectMeta.Annotations = map[string]string{
"konghq.com/tags": "tag1,tag2",
}
return obj
}(),
expectedTags: []string{
"k8s-generation:2",
"k8s-group:test.objects.io",
"k8s-kind:TestObjectKind",
"k8s-name:test-object",
"k8s-namespace:test-namespace",
"k8s-uid:test-uid",
"k8s-version:v1",
"tag1",
"tag2",
},
},
{
name: "additional tags are passed with a duplicate",
obj: func() testObjectKind {
obj := namespacedObject()
obj.ObjectMeta.Annotations = map[string]string{
"konghq.com/tags": "tag1,tag2,duplicate-tag",
}
return obj
}(),
additionalTags: []string{"tag3", "duplicate-tag"},
expectedTags: []string{
"duplicate-tag",
"k8s-generation:2",
"k8s-group:test.objects.io",
"k8s-kind:TestObjectKind",
"k8s-name:test-object",
"k8s-namespace:test-namespace",
"k8s-uid:test-uid",
"k8s-version:v1",
"tag1",
"tag2",
"tag3",
},
},
}

for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
tags := ops.GenerateKubernetesMetadataTags(&tc.obj)
tags := ops.GenerateTagsForObject(&tc.obj, tc.additionalTags...)
require.Equal(t, tc.expectedTags, tags)
})
}
Expand Down
12 changes: 1 addition & 11 deletions controller/konnect/ops/ops_credentialacl.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"slices"

sdkkonnectcomp "github.com/Kong/sdk-konnect-go/models/components"
sdkkonnectops "github.com/Kong/sdk-konnect-go/models/operations"
Expand All @@ -14,7 +13,6 @@ import (
ctrllog "sigs.k8s.io/controller-runtime/pkg/log"

configurationv1alpha1 "github.com/kong/kubernetes-configuration/api/configuration/v1alpha1"
"github.com/kong/kubernetes-configuration/pkg/metadata"
)

func createKongCredentialACL(
Expand Down Expand Up @@ -149,16 +147,8 @@ func deleteKongCredentialACL(
func kongCredentialACLToACLWithoutParents(
cred *configurationv1alpha1.KongCredentialACL,
) sdkkonnectcomp.ACLWithoutParents {
var (
specTags = cred.Spec.Tags
annotationTags = metadata.ExtractTags(cred)
k8sTags = GenerateKubernetesMetadataTags(cred)
)
// Deduplicate tags to avoid rejection by Konnect.
tags := lo.Uniq(slices.Concat(specTags, annotationTags, k8sTags))

return sdkkonnectcomp.ACLWithoutParents{
Group: lo.ToPtr(cred.Spec.Group),
Tags: tags,
Tags: GenerateTagsForObject(cred, cred.Spec.Tags...),
}
}
12 changes: 1 addition & 11 deletions controller/konnect/ops/ops_credentialapikey.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"slices"

sdkkonnectcomp "github.com/Kong/sdk-konnect-go/models/components"
sdkkonnectops "github.com/Kong/sdk-konnect-go/models/operations"
Expand All @@ -14,7 +13,6 @@ import (
ctrllog "sigs.k8s.io/controller-runtime/pkg/log"

configurationv1alpha1 "github.com/kong/kubernetes-configuration/api/configuration/v1alpha1"
"github.com/kong/kubernetes-configuration/pkg/metadata"
)

func createKongCredentialAPIKey(
Expand Down Expand Up @@ -128,16 +126,8 @@ func deleteKongCredentialAPIKey(
func kongCredentialAPIKeyToKeyAuthWithoutParents(
cred *configurationv1alpha1.KongCredentialAPIKey,
) sdkkonnectcomp.KeyAuthWithoutParents {
var (
specTags = cred.Spec.Tags
annotationTags = metadata.ExtractTags(cred)
k8sTags = GenerateKubernetesMetadataTags(cred)
)
// Deduplicate tags to avoid rejection by Konnect.
tags := lo.Uniq(slices.Concat(specTags, annotationTags, k8sTags))

return sdkkonnectcomp.KeyAuthWithoutParents{
Key: lo.ToPtr(cred.Spec.Key),
Tags: tags,
Tags: GenerateTagsForObject(cred, cred.Spec.Tags...),
}
}
12 changes: 1 addition & 11 deletions controller/konnect/ops/ops_credentialbasicauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"errors"
"fmt"
"slices"

sdkkonnectcomp "github.com/Kong/sdk-konnect-go/models/components"
sdkkonnectops "github.com/Kong/sdk-konnect-go/models/operations"
Expand All @@ -14,7 +13,6 @@ import (
ctrllog "sigs.k8s.io/controller-runtime/pkg/log"

configurationv1alpha1 "github.com/kong/kubernetes-configuration/api/configuration/v1alpha1"
"github.com/kong/kubernetes-configuration/pkg/metadata"
)

func createKongCredentialBasicAuth(
Expand Down Expand Up @@ -127,17 +125,9 @@ func deleteKongCredentialBasicAuth(
func kongCredentialBasicAuthToBasicAuthWithoutParents(
cred *configurationv1alpha1.KongCredentialBasicAuth,
) sdkkonnectcomp.BasicAuthWithoutParents {
var (
specTags = cred.Spec.Tags
annotationTags = metadata.ExtractTags(cred)
k8sTags = GenerateKubernetesMetadataTags(cred)
)
// Deduplicate tags to avoid rejection by Konnect.
tags := lo.Uniq(slices.Concat(specTags, annotationTags, k8sTags))

return sdkkonnectcomp.BasicAuthWithoutParents{
Password: lo.ToPtr(cred.Spec.Password),
Username: lo.ToPtr(cred.Spec.Username),
Tags: tags,
Tags: GenerateTagsForObject(cred, cred.Spec.Tags...),
}
}
10 changes: 1 addition & 9 deletions controller/konnect/ops/ops_kongcacertificate.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,14 @@ import (
"context"
"errors"
"fmt"
"slices"

sdkkonnectcomp "github.com/Kong/sdk-konnect-go/models/components"
sdkkonnectops "github.com/Kong/sdk-konnect-go/models/operations"
sdkkonnecterrs "github.com/Kong/sdk-konnect-go/models/sdkerrors"
"github.com/samber/lo"
"sigs.k8s.io/controller-runtime/pkg/client"
ctrllog "sigs.k8s.io/controller-runtime/pkg/log"

configurationv1alpha1 "github.com/kong/kubernetes-configuration/api/configuration/v1alpha1"
"github.com/kong/kubernetes-configuration/pkg/metadata"
)

// createCACertificate creates a KongCACertificate in Konnect.
Expand Down Expand Up @@ -117,14 +114,9 @@ func deleteCACertificate(
}

func kongCACertificateToCACertificateInput(cert *configurationv1alpha1.KongCACertificate) sdkkonnectcomp.CACertificateInput {
var (
annotationTags = metadata.ExtractTags(cert)
specTags = cert.Spec.Tags
k8sMetaTags = GenerateKubernetesMetadataTags(cert)
)
return sdkkonnectcomp.CACertificateInput{
Cert: cert.Spec.Cert,
// Deduplicate tags to avoid rejection by Konnect.
Tags: lo.Uniq(slices.Concat(annotationTags, specTags, k8sMetaTags)),
Tags: GenerateTagsForObject(cert, cert.Spec.Tags...),
}
}
Loading
Loading