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: make kind optional in k8s config relationships #334

Merged
merged 1 commit into from
Dec 13, 2023
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
7 changes: 7 additions & 0 deletions api/v1/kubernetes.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ func (t *KubernetesRelationshipLookup) Eval(labels map[string]string, envVar map
return "", errors.New("unknown kubernetes relationship lookup type")
}

func (t KubernetesRelationshipLookup) IsEmpty() bool {
if t.Value == "" && t.Label == "" && t.Expr == "" {
return true
}
return false
}

type KubernetesRelationship struct {
// Kind defines which field to use for the kind lookup
Kind KubernetesRelationshipLookup `json:"kind" yaml:"kind"`
Expand Down
47 changes: 19 additions & 28 deletions scrapers/kubernetes/kubernetes.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package kubernetes

import (
"fmt"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -40,7 +39,7 @@ func (kubernetes KubernetesScraper) Scrape(ctx api.ScrapeContext) v1.ScrapeResul

for _, config := range ctx.ScrapeConfig().Spec.Kubernetes {
if config.ClusterName == "" {
logger.Fatalf("clusterName missing from kubernetes configuration")
return results.Errorf(err, "clusterName missing from kubernetes configuration")
}

// Add Cluster object first
Expand Down Expand Up @@ -133,13 +132,17 @@ func (kubernetes KubernetesScraper) Scrape(ctx api.ScrapeContext) v1.ScrapeResul
env["spec"] = map[string]any{}
}

kind, err := f.Kind.Eval(obj.GetLabels(), env)
if err != nil {
return results.Errorf(err, "failed to evaluate kind: %v for config relationship", f.Kind)
}
var kind string
if !f.Kind.IsEmpty() {
kind, err = f.Kind.Eval(obj.GetLabels(), env)
if err != nil {
return results.Errorf(err, "failed to evaluate kind: %v for config relationship", f.Kind)
}

if kind != obj.GetKind() {
continue // Try matching another relationship
if kind != obj.GetKind() {
// Try matching another relationship
continue
}
}

name, err := f.Name.Eval(obj.GetLabels(), env)
Expand Down Expand Up @@ -170,21 +173,14 @@ func (kubernetes KubernetesScraper) Scrape(ctx api.ScrapeContext) v1.ScrapeResul
}
}

obj.SetManagedFields(nil)
annotations := obj.GetAnnotations()
if annotations != nil {
delete(annotations, "kubectl.kubernetes.io/last-applied-configuration")
}
obj.SetAnnotations(annotations)
metadata := obj.Object["metadata"].(map[string]interface{})
tags := make(map[string]interface{})
if metadata["labels"] != nil {
tags = metadata["labels"].(map[string]interface{})
tags := make(map[string]string)
if obj.GetLabels() != nil {
tags = obj.GetLabels()
}
tags["cluster"] = config.ClusterName
if obj.GetNamespace() != "" {
tags["namespace"] = obj.GetNamespace()
}
tags["cluster"] = config.ClusterName

// Add health metadata
var status, description string
Expand Down Expand Up @@ -228,7 +224,7 @@ func (kubernetes KubernetesScraper) Scrape(ctx api.ScrapeContext) v1.ScrapeResul
DeleteReason: deleteReason,
Config: cleanKubernetesObject(obj.Object),
ID: string(obj.GetUID()),
Tags: stripLabels(convertStringInterfaceMapToStringMap(tags), "-hash"),
Tags: stripLabels(tags, "-hash"),
Aliases: getKubernetesAlias(obj),
ParentExternalID: parentExternalID,
ParentType: ConfigTypePrefix + parentType,
Expand All @@ -241,14 +237,6 @@ func (kubernetes KubernetesScraper) Scrape(ctx api.ScrapeContext) v1.ScrapeResul
return results
}

func convertStringInterfaceMapToStringMap(input map[string]interface{}) map[string]string {
output := make(map[string]string)
for key, value := range input {
output[key] = fmt.Sprintf("%v", value)
}
return output
}

func getKubernetesParent(obj *unstructured.Unstructured, resourceIDMap map[string]map[string]map[string]string) (string, string) {
var parentExternalID, parentConfigType string

Expand Down Expand Up @@ -338,6 +326,9 @@ func cleanKubernetesObject(obj map[string]any) string {
o.Delete("metadata", "generation")
o.Delete("metadata", "resourceVersion")
o.Delete("metadata", "annotations", "control-plane.alpha.kubernetes.io/leader")
o.Delete("metadata", "annotations", "kubectl.kubernetes.io/last-applied-configuration")
o.Delete("metadata", "managedFields")

o.Delete("status", "artifact", "lastUpdateTime")
o.Delete("status", "observedGeneration")
o.Delete("status", "lastTransitionTime")
Expand Down
32 changes: 23 additions & 9 deletions scrapers/runscrapers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,18 +45,18 @@ var _ = Describe("Scrapers test", Ordered, func() {

It("should prepare scrape config", func() {
scrapeConfig = getConfigSpec("kubernetes")
scrapeConfig.Spec.Kubernetes[0].Exclusions = nil
scrapeConfig.Spec.Kubernetes[0].Kubeconfig = &types.EnvVar{
ValueStatic: kubeConfigPath,
}
scrapeConfig.Spec.Kubernetes[0].Relationships = append(scrapeConfig.Spec.Kubernetes[0].Relationships, v1.KubernetesRelationship{
Kind: v1.KubernetesRelationshipLookup{Value: "ConfigMap"},
Name: v1.KubernetesRelationshipLookup{Label: "flanksource/name"},
Namespace: v1.KubernetesRelationshipLookup{Label: "flanksource/namespace"},
})
})

It("should save a configMap", func() {
first := &apiv1.ConfigMap{
cm1 := &apiv1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "first-config",
Namespace: "default",
Expand All @@ -68,20 +68,35 @@ var _ = Describe("Scrapers test", Ordered, func() {
Data: map[string]string{"key": "value"},
}

err := k8sClient.Create(gocontext.TODO(), first)
err := k8sClient.Create(gocontext.Background(), cm1)
Expect(err).NotTo(HaveOccurred(), "failed to create test MyKind resource")

sec1 := &apiv1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "first-secret",
Namespace: "default",
Labels: map[string]string{
"flanksource/name": "second-config",
"flanksource/namespace": "default",
},
},
Data: nil,
}

err = k8sClient.Create(gocontext.Background(), sec1)
Expect(err).NotTo(HaveOccurred(), "failed to create test MyKind resource")
})

It("should save second configMap", func() {
first := &apiv1.ConfigMap{
cm2 := &apiv1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "second-config",
Namespace: "default",
},
Data: map[string]string{"key": "value"},
}

err := k8sClient.Create(gocontext.TODO(), first)
err := k8sClient.Create(gocontext.Background(), cm2)
Expect(err).NotTo(HaveOccurred(), "failed to create test MyKind resource")
})

Expand All @@ -93,10 +108,10 @@ var _ = Describe("Scrapers test", Ordered, func() {

It("should have saved the two config items to database", func() {
var configItems []models.ConfigItem
err := gormDB.Where("name IN (?, ?)", "first-config", "second-config").Find(&configItems).Error
err := gormDB.Where("name IN (?, ?, ?)", "first-config", "second-config", "first-secret").Find(&configItems).Error
Expect(err).To(BeNil())

Expect(len(configItems)).To(Equal(2))
Expect(len(configItems)).To(Equal(3))
})

It("should correctly setup kubernetes relationship", func() {
Expand All @@ -108,8 +123,7 @@ var _ = Describe("Scrapers test", Ordered, func() {
err = gormDB.Find(&configRelationships).Error
Expect(err).To(BeNil())

Expect(len(configRelationships)).To(Equal(1))
Expect(configRelationships[0].Relation).To(Equal("ConfigMapConfigMap"))
Expect(len(configRelationships)).To(Equal(2))
})
})

Expand Down
Loading