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

[processor/resourcedetection] Add k8s.cluster.uid to kubeadm detector #38216

Merged
merged 4 commits into from
Feb 26, 2025
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
27 changes: 27 additions & 0 deletions .chloggen/kubeadm-uid.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Use this changelog template to create an entry for release notes.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: enhancement

# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
component: processor/resourcedetection

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: "Add k8s.cluster.uid to kubeadm detector"

# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists.
issues: [38207]

# (Optional) One or more lines of additional information to render under the primary note.
# These lines will be padded with 2 spaces and then inserted directly into the document.
# Use pipe (|) for multiline entries.
subtext:

# If your change doesn't affect end users or the exported elements of any package,
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.
# Optional: The change log or logs in which this entry should be included.
# e.g. '[user]' or '[user, api]'
# Include 'user' if the change is relevant to end users.
# Include 'api' if there is a change to a library API.
# Default: '[user]'
change_logs: []
37 changes: 27 additions & 10 deletions internal/metadataproviders/kubeadm/metadata.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,41 +16,58 @@ import (
type Provider interface {
// ClusterName returns the current K8S cluster name
ClusterName(ctx context.Context) (string, error)
// ClusterUID returns the current K8S cluster UID
ClusterUID(ctx context.Context) (string, error)
}

type LocalCache struct {
ClusterName string
ClusterUID string
}

type kubeadmProvider struct {
kubeadmClient kubernetes.Interface
configMapName string
configMapNamespace string
cache LocalCache
kubeadmClient kubernetes.Interface
configMapName string
kubeSystemNamespace string
cache LocalCache
}

func NewProvider(configMapName string, configMapNamespace string, apiConf k8sconfig.APIConfig) (Provider, error) {
func NewProvider(configMapName string, kubeSystemNamespace string, apiConf k8sconfig.APIConfig) (Provider, error) {
k8sAPIClient, err := k8sconfig.MakeClient(apiConf)
if err != nil {
return nil, fmt.Errorf("failed to create K8s API client: %w", err)
}
return &kubeadmProvider{
kubeadmClient: k8sAPIClient,
configMapName: configMapName,
configMapNamespace: configMapNamespace,
kubeadmClient: k8sAPIClient,
configMapName: configMapName,
kubeSystemNamespace: kubeSystemNamespace,
}, nil
}

func (k *kubeadmProvider) ClusterName(ctx context.Context) (string, error) {
if k.cache.ClusterName != "" {
return k.cache.ClusterName, nil
}
configmap, err := k.kubeadmClient.CoreV1().ConfigMaps(k.configMapNamespace).Get(ctx, k.configMapName, metav1.GetOptions{})
configmap, err := k.kubeadmClient.CoreV1().ConfigMaps(k.kubeSystemNamespace).Get(ctx, k.configMapName, metav1.GetOptions{})
if err != nil {
return "", fmt.Errorf("failed to fetch ConfigMap with name %s and namespace %s from K8s API: %w", k.configMapName, k.configMapNamespace, err)
return "", fmt.Errorf("failed to fetch ConfigMap with name %s and namespace %s from K8s API: %w", k.configMapName, k.kubeSystemNamespace, err)
}

k.cache.ClusterName = configmap.Data["clusterName"]

return k.cache.ClusterName, nil
}

func (k *kubeadmProvider) ClusterUID(ctx context.Context) (string, error) {
if k.cache.ClusterUID != "" {
return k.cache.ClusterUID, nil
}
ns, err := k.kubeadmClient.CoreV1().Namespaces().Get(ctx, k.kubeSystemNamespace, metav1.GetOptions{})
if err != nil {
return "", fmt.Errorf("failed to fetch Namespace %s from K8s API: %w", k.kubeSystemNamespace, err)
}

k.cache.ClusterUID = string(ns.GetUID())

return k.cache.ClusterUID, nil
}
62 changes: 59 additions & 3 deletions internal/metadataproviders/kubeadm/metadata_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/kubernetes/fake"

"github.com/open-telemetry/opentelemetry-collector-contrib/internal/k8sconfig"
Expand Down Expand Up @@ -54,9 +55,9 @@ func TestClusterName(t *testing.T) {
for _, tt := range tests {
t.Run(tt.testName, func(t *testing.T) {
kubeadmP := &kubeadmProvider{
kubeadmClient: client,
configMapName: tt.CMname,
configMapNamespace: tt.CMnamespace,
kubeadmClient: client,
configMapName: tt.CMname,
kubeSystemNamespace: tt.CMnamespace,
}
clusterName, err := kubeadmP.ClusterName(context.Background())
if tt.errMsg != "" {
Expand All @@ -69,6 +70,47 @@ func TestClusterName(t *testing.T) {
}
}

func TestClusterUID(t *testing.T) {
client := fake.NewSimpleClientset()
err := setupNamespace(client)
assert.NoError(t, err)

tests := []struct {
testName string
CMnamespace string
clusterUID string
errMsg string
}{
{
testName: "valid",
CMnamespace: "ns",
clusterUID: "uid",
errMsg: "",
},
{
testName: "ns not found",
CMnamespace: "ns2",
errMsg: "failed to fetch Namespace ns2 from K8s API: namespaces \"ns2\" not found",
},
}

for _, tt := range tests {
t.Run(tt.testName, func(t *testing.T) {
kubeadmP := &kubeadmProvider{
kubeadmClient: client,
kubeSystemNamespace: tt.CMnamespace,
}
clusterName, err := kubeadmP.ClusterUID(context.Background())
if tt.errMsg != "" {
assert.EqualError(t, err, tt.errMsg)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.clusterUID, clusterName)
}
})
}
}

func setupConfigMap(client *fake.Clientset) error {
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Expand All @@ -85,3 +127,17 @@ func setupConfigMap(client *fake.Clientset) error {
}
return nil
}

func setupNamespace(client *fake.Clientset) error {
ns := &corev1.Namespace{
ObjectMeta: metav1.ObjectMeta{
UID: types.UID("uid"),
Name: "ns",
},
}
_, err := client.CoreV1().Namespaces().Create(context.Background(), ns, metav1.CreateOptions{})
if err != nil {
return err
}
return nil
}
4 changes: 4 additions & 0 deletions processor/resourcedetectionprocessor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,10 @@ rules:
resources: ["configmaps"]
resourceNames: ["kubeadm-config"]
verbs: ["get"]
- apiGroups: [""]
resources: ["namespaces"]
resourceNames: ["kube-system"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@
| Name | Description | Values | Enabled |
| ---- | ----------- | ------ | ------- |
| k8s.cluster.name | The Kubernetes cluster name | Any Str | true |
| k8s.cluster.uid | The Kubernetes cluster UID | Any Str | true |

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@ all_set:
resource_attributes:
k8s.cluster.name:
enabled: true
k8s.cluster.uid:
enabled: true
none_set:
resource_attributes:
k8s.cluster.name:
enabled: false
k8s.cluster.uid:
enabled: false
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ import (
)

const (
TypeStr = "kubeadm"
defaultConfigMapName = "kubeadm-config"
defaultConfigMapNamespace = "kube-system"
TypeStr = "kubeadm"
defaultConfigMapName = "kubeadm-config"
defaultKubeSystemNamespace = "kube-system"
)

var _ internal.Detector = (*detector)(nil)
Expand All @@ -35,7 +35,7 @@ type detector struct {
func NewDetector(set processor.Settings, dcfg internal.DetectorConfig) (internal.Detector, error) {
cfg := dcfg.(Config)

kubeadmProvider, err := kubeadm.NewProvider(defaultConfigMapName, defaultConfigMapNamespace, cfg.APIConfig)
kubeadmProvider, err := kubeadm.NewProvider(defaultConfigMapName, defaultKubeSystemNamespace, cfg.APIConfig)
if err != nil {
return nil, fmt.Errorf("failed creating kubeadm provider: %w", err)
}
Expand All @@ -57,5 +57,13 @@ func (d *detector) Detect(ctx context.Context) (resource pcommon.Resource, schem
d.rb.SetK8sClusterName(clusterName)
}

if d.ra.K8sClusterUID.Enabled {
clusterUID, err := d.provider.ClusterUID(ctx)
if err != nil {
return pcommon.NewResource(), "", fmt.Errorf("failed getting k8s cluster uid: %w", err)
}
d.rb.SetK8sClusterUID(clusterUID)
}

return d.rb.Emit(), conventions.SchemaURL, nil
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,15 @@ func (m *mockMetadata) ClusterName(_ context.Context) (string, error) {
return args.String(0), args.Error(1)
}

func (m *mockMetadata) ClusterUID(_ context.Context) (string, error) {
args := m.MethodCalled("ClusterUID")
return args.String(0), args.Error(1)
}

func TestDetect(t *testing.T) {
md := &mockMetadata{}
md.On("ClusterName").Return("cluster-1", nil)
md.On("ClusterUID").Return("uid-1", nil)
cfg := CreateDefaultConfig()
// set k8s cluster env variables and auth type to create a dummy API client
cfg.APIConfig.AuthType = k8sconfig.AuthTypeNone
Expand All @@ -47,6 +53,7 @@ func TestDetect(t *testing.T) {

expected := map[string]any{
conventions.AttributeK8SClusterName: "cluster-1",
"k8s.cluster.uid": "uid-1",
}

assert.Equal(t, expected, res.Attributes().AsRaw())
Expand All @@ -56,6 +63,7 @@ func TestDetectDisabledResourceAttributes(t *testing.T) {
md := &mockMetadata{}
cfg := CreateDefaultConfig()
cfg.ResourceAttributes.K8sClusterName.Enabled = false
cfg.ResourceAttributes.K8sClusterUID.Enabled = false
// set k8s cluster env variables and auth type to create a dummy API client
cfg.APIConfig.AuthType = k8sconfig.AuthTypeNone
t.Setenv("KUBERNETES_SERVICE_HOST", "127.0.0.1")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,7 @@ resource_attributes:
description: The Kubernetes cluster name
type: string
enabled: true
k8s.cluster.uid:
description: The Kubernetes cluster UID
type: string
enabled: true
Loading