Skip to content

Commit

Permalink
[processor/resourcedetection] introduce kubeadm detector (open-teleme…
Browse files Browse the repository at this point in the history
…try#35450)

**Description:** <Describe what has changed.>
<!--Ex. Fixing a bug - Describe the bug and how this fixes the issue.
Ex. Adding a feature - Explain what this achieves.-->
- introduce `kubeadm` detector to detect local cluster name

**Link to tracking Issue:** open-telemetry#35116

---------

Signed-off-by: odubajDT <ondrej.dubaj@dynatrace.com>
Co-authored-by: Christos Markou <chrismarkou92@gmail.com>
  • Loading branch information
odubajDT and ChrsMark authored Jan 13, 2025
1 parent 667e81e commit 981e9f5
Show file tree
Hide file tree
Showing 20 changed files with 615 additions and 0 deletions.
27 changes: 27 additions & 0 deletions .chloggen/resourcedetection-local-cluster.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: resourcedetectionprocessor

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

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

# (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: []
56 changes: 56 additions & 0 deletions internal/metadataproviders/kubeadm/metadata.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package kubeadm // import "github.com/open-telemetry/opentelemetry-collector-contrib/internal/metadataproviders/kubeadm"

import (
"context"
"fmt"

metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"

"github.com/open-telemetry/opentelemetry-collector-contrib/internal/k8sconfig"
)

type Provider interface {
// ClusterName returns the current K8S cluster name
ClusterName(ctx context.Context) (string, error)
}

type LocalCache struct {
ClusterName string
}

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

func NewProvider(configMapName string, configMapNamespace 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,
}, 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{})
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)
}

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

return k.cache.ClusterName, nil
}
87 changes: 87 additions & 0 deletions internal/metadataproviders/kubeadm/metadata_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package kubeadm

import (
"context"
"testing"

"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes/fake"

"github.com/open-telemetry/opentelemetry-collector-contrib/internal/k8sconfig"
)

func TestNewProvider(t *testing.T) {
// set k8s cluster env variables to make the API client happy
t.Setenv("KUBERNETES_SERVICE_HOST", "127.0.0.1")
t.Setenv("KUBERNETES_SERVICE_PORT", "6443")

_, err := NewProvider("name", "ns", k8sconfig.APIConfig{AuthType: k8sconfig.AuthTypeNone})
assert.NoError(t, err)
}

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

tests := []struct {
testName string
CMname string
CMnamespace string
clusterName string
errMsg string
}{
{
testName: "valid",
CMname: "cm",
CMnamespace: "ns",
clusterName: "myClusterName",
errMsg: "",
},
{
testName: "configmap not found",
CMname: "cm2",
CMnamespace: "ns",
errMsg: "failed to fetch ConfigMap with name cm2 and namespace ns from K8s API: configmaps \"cm2\" not found",
},
}

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

func setupConfigMap(client *fake.Clientset) error {
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: "cm",
Namespace: "ns",
},
Data: map[string]string{
"clusterName": "myClusterName",
},
}
_, err := client.CoreV1().ConfigMaps("ns").Create(context.Background(), cm, metav1.CreateOptions{})
if err != nil {
return err
}
return nil
}
14 changes: 14 additions & 0 deletions internal/metadataproviders/kubeadm/package_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package kubeadm

import (
"testing"

"go.uber.org/goleak"
)

func TestMain(m *testing.M) {
goleak.VerifyTestMain(m)
}
37 changes: 37 additions & 0 deletions processor/resourcedetectionprocessor/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,43 @@ processors:
override: false
```

### Kubeadm Metadata

Queries the K8S API server to retrieve kubeadm resource attributes:

The list of the populated resource attributes can be found at [kubeadm Detector Resource Attributes](./internal/kubeadm/documentation.md).

The following permissions are required:
```yaml
kind: Role
metadata:
name: otel-collector
namespace: kube-system
rules:
- apiGroups: [""]
resources: ["configmaps"]
resourceNames: ["kubeadm-config"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: otel-collector-rolebinding
namespace: kube-system
subjects:
- kind: ServiceAccount
name: default
namespace: default
roleRef:
kind: Role
name: otel-collector
apiGroup: rbac.authorization.k8s.io
```

| Name | Type | Required | Default | Docs |
| ---- | ---- |----------|-----------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| auth_type | string | No | `serviceAccount` | How to authenticate to the K8s API server. This can be one of `none` (for no auth), `serviceAccount` (to use the standard service account token provided to the agent pod), or `kubeConfig` to use credentials from `~/.kube/config`. |

### K8S Node Metadata

Queries the K8S api server to retrieve node resource attributes.
Expand Down
7 changes: 7 additions & 0 deletions processor/resourcedetectionprocessor/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"github.com/open-telemetry/opentelemetry-collector-contrib/processor/resourcedetectionprocessor/internal/gcp"
"github.com/open-telemetry/opentelemetry-collector-contrib/processor/resourcedetectionprocessor/internal/heroku"
"github.com/open-telemetry/opentelemetry-collector-contrib/processor/resourcedetectionprocessor/internal/k8snode"
"github.com/open-telemetry/opentelemetry-collector-contrib/processor/resourcedetectionprocessor/internal/kubeadm"
"github.com/open-telemetry/opentelemetry-collector-contrib/processor/resourcedetectionprocessor/internal/openshift"
"github.com/open-telemetry/opentelemetry-collector-contrib/processor/resourcedetectionprocessor/internal/system"
)
Expand Down Expand Up @@ -85,6 +86,9 @@ type DetectorConfig struct {

// K8SNode contains user-specified configurations for the K8SNode detector
K8SNodeConfig k8snode.Config `mapstructure:"k8snode"`

// Kubeadm contains user-specified configurations for the Kubeadm detector
KubeadmConfig kubeadm.Config `mapstructure:"kubeadm"`
}

func detectorCreateDefaultConfig() DetectorConfig {
Expand All @@ -103,6 +107,7 @@ func detectorCreateDefaultConfig() DetectorConfig {
SystemConfig: system.CreateDefaultConfig(),
OpenShiftConfig: openshift.CreateDefaultConfig(),
K8SNodeConfig: k8snode.CreateDefaultConfig(),
KubeadmConfig: kubeadm.CreateDefaultConfig(),
}
}

Expand Down Expand Up @@ -136,6 +141,8 @@ func (d *DetectorConfig) GetConfigFromType(detectorType internal.DetectorType) i
return d.OpenShiftConfig
case k8snode.TypeStr:
return d.K8SNodeConfig
case kubeadm.TypeStr:
return d.KubeadmConfig
default:
return nil
}
Expand Down
1 change: 1 addition & 0 deletions processor/resourcedetectionprocessor/doc.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
//go:generate mdatagen internal/openshift/metadata.yaml
//go:generate mdatagen internal/system/metadata.yaml
//go:generate mdatagen internal/k8snode/metadata.yaml
//go:generate mdatagen internal/kubeadm/metadata.yaml

// package resourcedetectionprocessor implements a processor
// which can be used to detect resource information from the host,
Expand Down
2 changes: 2 additions & 0 deletions processor/resourcedetectionprocessor/factory.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ import (
"github.com/open-telemetry/opentelemetry-collector-contrib/processor/resourcedetectionprocessor/internal/gcp"
"github.com/open-telemetry/opentelemetry-collector-contrib/processor/resourcedetectionprocessor/internal/heroku"
"github.com/open-telemetry/opentelemetry-collector-contrib/processor/resourcedetectionprocessor/internal/k8snode"
"github.com/open-telemetry/opentelemetry-collector-contrib/processor/resourcedetectionprocessor/internal/kubeadm"
"github.com/open-telemetry/opentelemetry-collector-contrib/processor/resourcedetectionprocessor/internal/metadata"
"github.com/open-telemetry/opentelemetry-collector-contrib/processor/resourcedetectionprocessor/internal/openshift"
"github.com/open-telemetry/opentelemetry-collector-contrib/processor/resourcedetectionprocessor/internal/system"
Expand Down Expand Up @@ -66,6 +67,7 @@ func NewFactory() processor.Factory {
system.TypeStr: system.NewDetector,
openshift.TypeStr: openshift.NewDetector,
k8snode.TypeStr: k8snode.NewDetector,
kubeadm.TypeStr: kubeadm.NewDetector,
})

f := &factory{
Expand Down
21 changes: 21 additions & 0 deletions processor/resourcedetectionprocessor/internal/kubeadm/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

package kubeadm // import "github.com/open-telemetry/opentelemetry-collector-contrib/processor/resourcedetectionprocessor/internal/kubeadm"

import (
"github.com/open-telemetry/opentelemetry-collector-contrib/internal/k8sconfig"
"github.com/open-telemetry/opentelemetry-collector-contrib/processor/resourcedetectionprocessor/internal/kubeadm/internal/metadata"
)

type Config struct {
k8sconfig.APIConfig `mapstructure:",squash"`
ResourceAttributes metadata.ResourceAttributesConfig `mapstructure:"resource_attributes"`
}

func CreateDefaultConfig() Config {
return Config{
APIConfig: k8sconfig.APIConfig{AuthType: k8sconfig.AuthTypeServiceAccount},
ResourceAttributes: metadata.DefaultResourceAttributesConfig(),
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)

# resourcedetectionprocessor/kubeadm

**Parent Component:** resourcedetection

## Resource Attributes

| Name | Description | Values | Enabled |
| ---- | ----------- | ------ | ------- |
| k8s.cluster.name | The Kubernetes cluster name | 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.

Loading

0 comments on commit 981e9f5

Please sign in to comment.