diff --git a/.chloggen/switchk8sdeployment.yaml b/.chloggen/switchk8sdeployment.yaml new file mode 100755 index 000000000000..4c9be60c4a66 --- /dev/null +++ b/.chloggen/switchk8sdeployment.yaml @@ -0,0 +1,11 @@ +# 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: k8sclusterreceiver + +# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`). +note: Switch k8s.deployment metrics to use pdata. + +# One or more tracking issues related to the change +issues: [23416] diff --git a/pkg/pdatatest/pmetrictest/options.go b/pkg/pdatatest/pmetrictest/options.go index 9e7b57c2ca5b..06e874fccb35 100644 --- a/pkg/pdatatest/pmetrictest/options.go +++ b/pkg/pdatatest/pmetrictest/options.go @@ -315,6 +315,24 @@ func sortResourceMetricsSlice(rms pmetric.ResourceMetricsSlice) { }) } +func IgnoreScopeVersion() CompareMetricsOption { + return compareMetricsOptionFunc(func(expected, actual pmetric.Metrics) { + maskScopeVersion(expected) + maskScopeVersion(actual) + }) +} + +func maskScopeVersion(metrics pmetric.Metrics) { + rms := metrics.ResourceMetrics() + for i := 0; i < rms.Len(); i++ { + rm := rms.At(i) + for j := 0; j < rm.ScopeMetrics().Len(); j++ { + sm := rm.ScopeMetrics().At(j) + sm.Scope().SetVersion("") + } + } +} + // IgnoreScopeMetricsOrder is a CompareMetricsOption that ignores the order of instrumentation scope traces/metrics/logs. func IgnoreScopeMetricsOrder() CompareMetricsOption { return compareMetricsOptionFunc(func(expected, actual pmetric.Metrics) { diff --git a/receiver/k8sclusterreceiver/e2e_test.go b/receiver/k8sclusterreceiver/e2e_test.go index ed279eb95749..94d5cfbc5146 100644 --- a/receiver/k8sclusterreceiver/e2e_test.go +++ b/receiver/k8sclusterreceiver/e2e_test.go @@ -100,6 +100,7 @@ func TestE2E(t *testing.T) { pmetrictest.ChangeResourceAttributeValue("k8s.namespace.uid", replaceWithStar), pmetrictest.ChangeResourceAttributeValue("k8s.daemonset.uid", replaceWithStar), pmetrictest.ChangeResourceAttributeValue("container.image.name", containerImageShorten), + pmetrictest.IgnoreScopeVersion(), pmetrictest.IgnoreResourceMetricsOrder(), pmetrictest.IgnoreMetricsOrder(), pmetrictest.IgnoreScopeMetricsOrder(), diff --git a/receiver/k8sclusterreceiver/internal/collection/collector.go b/receiver/k8sclusterreceiver/internal/collection/collector.go index d866a45f0113..153aee4a48d1 100644 --- a/receiver/k8sclusterreceiver/internal/collection/collector.go +++ b/receiver/k8sclusterreceiver/internal/collection/collector.go @@ -114,7 +114,7 @@ func (dc *DataCollector) SyncMetrics(obj interface{}) { case *corev1.ResourceQuota: md = resourcequota.GetMetrics(dc.settings, o) case *appsv1.Deployment: - md = ocsToMetrics(deployment.GetMetrics(o)) + md = deployment.GetMetrics(dc.settings, o) case *appsv1.ReplicaSet: md = ocsToMetrics(replicaset.GetMetrics(o)) case *appsv1.DaemonSet: diff --git a/receiver/k8sclusterreceiver/internal/deployment/deployments.go b/receiver/k8sclusterreceiver/internal/deployment/deployments.go index 2d46b3e2f33e..f4dd7e1e95af 100644 --- a/receiver/k8sclusterreceiver/internal/deployment/deployments.go +++ b/receiver/k8sclusterreceiver/internal/deployment/deployments.go @@ -4,43 +4,26 @@ package deployment // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/deployment" import ( - agentmetricspb "github.com/census-instrumentation/opencensus-proto/gen-go/agent/metrics/v1" - resourcepb "github.com/census-instrumentation/opencensus-proto/gen-go/resource/v1" + "time" + + "go.opentelemetry.io/collector/pdata/pcommon" + "go.opentelemetry.io/collector/pdata/pmetric" + "go.opentelemetry.io/collector/receiver" conventions "go.opentelemetry.io/collector/semconv/v1.6.1" appsv1 "k8s.io/api/apps/v1" "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/experimentalmetricmetadata" "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/constants" + imetadata "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/deployment/internal/metadata" "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/metadata" - "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/replica" ) -func GetMetrics(dep *appsv1.Deployment) []*agentmetricspb.ExportMetricsServiceRequest { - if dep.Spec.Replicas == nil { - return nil - } - - return []*agentmetricspb.ExportMetricsServiceRequest{ - { - Resource: getResource(dep), - Metrics: replica.GetMetrics( - "deployment", - *dep.Spec.Replicas, - dep.Status.AvailableReplicas, - ), - }, - } -} - -func getResource(dep *appsv1.Deployment) *resourcepb.Resource { - return &resourcepb.Resource{ - Type: constants.K8sType, - Labels: map[string]string{ - conventions.AttributeK8SDeploymentUID: string(dep.UID), - conventions.AttributeK8SDeploymentName: dep.Name, - conventions.AttributeK8SNamespaceName: dep.Namespace, - }, - } +func GetMetrics(set receiver.CreateSettings, dep *appsv1.Deployment) pmetric.Metrics { + mb := imetadata.NewMetricsBuilder(imetadata.DefaultMetricsBuilderConfig(), set) + ts := pcommon.NewTimestampFromTime(time.Now()) + mb.RecordK8sDeploymentDesiredDataPoint(ts, int64(*dep.Spec.Replicas)) + mb.RecordK8sDeploymentAvailableDataPoint(ts, int64(dep.Status.AvailableReplicas)) + return mb.Emit(imetadata.WithK8sDeploymentName(dep.Name), imetadata.WithK8sDeploymentUID(string(dep.UID)), imetadata.WithK8sNamespaceName(dep.Namespace), imetadata.WithOpencensusResourcetype("k8s")) } func GetMetadata(dep *appsv1.Deployment) map[experimentalmetricmetadata.ResourceID]*metadata.KubernetesMetadata { diff --git a/receiver/k8sclusterreceiver/internal/deployment/deployments_test.go b/receiver/k8sclusterreceiver/internal/deployment/deployments_test.go index 96d880725fc3..71677e588e67 100644 --- a/receiver/k8sclusterreceiver/internal/deployment/deployments_test.go +++ b/receiver/k8sclusterreceiver/internal/deployment/deployments_test.go @@ -4,35 +4,60 @@ package deployment import ( + "path/filepath" "testing" - metricspb "github.com/census-instrumentation/opencensus-proto/gen-go/metrics/v1" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "go.opentelemetry.io/collector/pdata/pmetric" + "go.opentelemetry.io/collector/receiver/receivertest" - "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/constants" + "github.com/open-telemetry/opentelemetry-collector-contrib/internal/coreinternal/golden" + "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/pdatatest/pmetrictest" "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/testutils" ) func TestDeploymentMetrics(t *testing.T) { dep := testutils.NewDeployment("1") - actualResourceMetrics := GetMetrics(dep) + m := GetMetrics(receivertest.NewNopCreateSettings(), dep) - require.Equal(t, 1, len(actualResourceMetrics)) - require.Equal(t, 2, len(actualResourceMetrics[0].Metrics)) + require.Equal(t, 1, m.ResourceMetrics().Len()) + require.Equal(t, 2, m.MetricCount()) - rm := actualResourceMetrics[0] - testutils.AssertResource(t, rm.Resource, constants.K8sType, - map[string]string{ - "k8s.deployment.uid": "test-deployment-1-uid", - "k8s.deployment.name": "test-deployment-1", - "k8s.namespace.name": "test-namespace", + rm := m.ResourceMetrics().At(0) + assert.Equal(t, + map[string]interface{}{ + "k8s.deployment.uid": "test-deployment-1-uid", + "k8s.deployment.name": "test-deployment-1", + "k8s.namespace.name": "test-namespace", + "opencensus.resourcetype": "k8s", }, + rm.Resource().Attributes().AsRaw(), ) + require.Equal(t, 1, rm.ScopeMetrics().Len()) + sms := rm.ScopeMetrics().At(0) + require.Equal(t, 2, sms.Metrics().Len()) + sms.Metrics().Sort(func(a, b pmetric.Metric) bool { + return a.Name() < b.Name() + }) + testutils.AssertMetricInt(t, sms.Metrics().At(0), "k8s.deployment.available", pmetric.MetricTypeGauge, int64(3)) + testutils.AssertMetricInt(t, sms.Metrics().At(1), "k8s.deployment.desired", pmetric.MetricTypeGauge, int64(10)) +} - testutils.AssertMetricsInt(t, rm.Metrics[0], "k8s.deployment.desired", - metricspb.MetricDescriptor_GAUGE_INT64, 10) - - testutils.AssertMetricsInt(t, rm.Metrics[1], "k8s.deployment.available", - metricspb.MetricDescriptor_GAUGE_INT64, 3) +func TestGoldenFile(t *testing.T) { + dep := testutils.NewDeployment("1") + m := GetMetrics(receivertest.NewNopCreateSettings(), dep) + expectedFile := filepath.Join("testdata", "expected.yaml") + expected, err := golden.ReadMetrics(expectedFile) + require.NoError(t, err) + require.NoError(t, pmetrictest.CompareMetrics(expected, m, + pmetrictest.IgnoreTimestamp(), + pmetrictest.IgnoreStartTimestamp(), + pmetrictest.IgnoreResourceMetricsOrder(), + pmetrictest.IgnoreMetricsOrder(), + pmetrictest.IgnoreScopeMetricsOrder(), + pmetrictest.IgnoreMetricDataPointsOrder(), + ), + ) } diff --git a/receiver/k8sclusterreceiver/internal/deployment/doc.go b/receiver/k8sclusterreceiver/internal/deployment/doc.go new file mode 100644 index 000000000000..2dc070726885 --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/deployment/doc.go @@ -0,0 +1,6 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +//go:generate mdatagen metadata.yaml + +package deployment // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/deployment" diff --git a/receiver/k8sclusterreceiver/internal/deployment/documentation.md b/receiver/k8sclusterreceiver/internal/deployment/documentation.md new file mode 100644 index 000000000000..ceebe838564b --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/deployment/documentation.md @@ -0,0 +1,38 @@ +[comment]: <> (Code generated by mdatagen. DO NOT EDIT.) + +# k8s/deployment + +## Default Metrics + +The following metrics are emitted by default. Each of them can be disabled by applying the following configuration: + +```yaml +metrics: + : + enabled: false +``` + +### k8s.deployment.available + +Total number of available pods (ready for at least minReadySeconds) targeted by this deployment + +| Unit | Metric Type | Value Type | +| ---- | ----------- | ---------- | +| 1 | Gauge | Int | + +### k8s.deployment.desired + +Number of desired pods in this deployment + +| Unit | Metric Type | Value Type | +| ---- | ----------- | ---------- | +| 1 | Gauge | Int | + +## Resource Attributes + +| Name | Description | Values | Enabled | +| ---- | ----------- | ------ | ------- | +| k8s.deployment.name | The name of the Deployment. | Any Str | true | +| k8s.deployment.uid | The UID of the Deployment. | Any Str | true | +| k8s.namespace.name | The name of the namespace that the pod is running in. | Any Str | true | +| opencensus.resourcetype | The OpenCensus resource type. | Any Str | true | diff --git a/receiver/k8sclusterreceiver/internal/deployment/internal/metadata/generated_config.go b/receiver/k8sclusterreceiver/internal/deployment/internal/metadata/generated_config.go new file mode 100644 index 000000000000..db880d354ec0 --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/deployment/internal/metadata/generated_config.go @@ -0,0 +1,84 @@ +// Code generated by mdatagen. DO NOT EDIT. + +package metadata + +import "go.opentelemetry.io/collector/confmap" + +// MetricConfig provides common config for a particular metric. +type MetricConfig struct { + Enabled bool `mapstructure:"enabled"` + + enabledSetByUser bool +} + +func (ms *MetricConfig) Unmarshal(parser *confmap.Conf) error { + if parser == nil { + return nil + } + err := parser.Unmarshal(ms, confmap.WithErrorUnused()) + if err != nil { + return err + } + ms.enabledSetByUser = parser.IsSet("enabled") + return nil +} + +// MetricsConfig provides config for k8s/deployment metrics. +type MetricsConfig struct { + K8sDeploymentAvailable MetricConfig `mapstructure:"k8s.deployment.available"` + K8sDeploymentDesired MetricConfig `mapstructure:"k8s.deployment.desired"` +} + +func DefaultMetricsConfig() MetricsConfig { + return MetricsConfig{ + K8sDeploymentAvailable: MetricConfig{ + Enabled: true, + }, + K8sDeploymentDesired: MetricConfig{ + Enabled: true, + }, + } +} + +// ResourceAttributeConfig provides common config for a particular resource attribute. +type ResourceAttributeConfig struct { + Enabled bool `mapstructure:"enabled"` +} + +// ResourceAttributesConfig provides config for k8s/deployment resource attributes. +type ResourceAttributesConfig struct { + K8sDeploymentName ResourceAttributeConfig `mapstructure:"k8s.deployment.name"` + K8sDeploymentUID ResourceAttributeConfig `mapstructure:"k8s.deployment.uid"` + K8sNamespaceName ResourceAttributeConfig `mapstructure:"k8s.namespace.name"` + OpencensusResourcetype ResourceAttributeConfig `mapstructure:"opencensus.resourcetype"` +} + +func DefaultResourceAttributesConfig() ResourceAttributesConfig { + return ResourceAttributesConfig{ + K8sDeploymentName: ResourceAttributeConfig{ + Enabled: true, + }, + K8sDeploymentUID: ResourceAttributeConfig{ + Enabled: true, + }, + K8sNamespaceName: ResourceAttributeConfig{ + Enabled: true, + }, + OpencensusResourcetype: ResourceAttributeConfig{ + Enabled: true, + }, + } +} + +// MetricsBuilderConfig is a configuration for k8s/deployment metrics builder. +type MetricsBuilderConfig struct { + Metrics MetricsConfig `mapstructure:"metrics"` + ResourceAttributes ResourceAttributesConfig `mapstructure:"resource_attributes"` +} + +func DefaultMetricsBuilderConfig() MetricsBuilderConfig { + return MetricsBuilderConfig{ + Metrics: DefaultMetricsConfig(), + ResourceAttributes: DefaultResourceAttributesConfig(), + } +} diff --git a/receiver/k8sclusterreceiver/internal/deployment/internal/metadata/generated_config_test.go b/receiver/k8sclusterreceiver/internal/deployment/internal/metadata/generated_config_test.go new file mode 100644 index 000000000000..86cc32765dba --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/deployment/internal/metadata/generated_config_test.go @@ -0,0 +1,74 @@ +// Code generated by mdatagen. DO NOT EDIT. + +package metadata + +import ( + "path/filepath" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/stretchr/testify/require" + "go.opentelemetry.io/collector/component" + "go.opentelemetry.io/collector/confmap/confmaptest" +) + +func TestMetricsBuilderConfig(t *testing.T) { + tests := []struct { + name string + want MetricsBuilderConfig + }{ + { + name: "default", + want: DefaultMetricsBuilderConfig(), + }, + { + name: "all_set", + want: MetricsBuilderConfig{ + Metrics: MetricsConfig{ + K8sDeploymentAvailable: MetricConfig{Enabled: true}, + K8sDeploymentDesired: MetricConfig{Enabled: true}, + }, + ResourceAttributes: ResourceAttributesConfig{ + K8sDeploymentName: ResourceAttributeConfig{Enabled: true}, + K8sDeploymentUID: ResourceAttributeConfig{Enabled: true}, + K8sNamespaceName: ResourceAttributeConfig{Enabled: true}, + OpencensusResourcetype: ResourceAttributeConfig{Enabled: true}, + }, + }, + }, + { + name: "none_set", + want: MetricsBuilderConfig{ + Metrics: MetricsConfig{ + K8sDeploymentAvailable: MetricConfig{Enabled: false}, + K8sDeploymentDesired: MetricConfig{Enabled: false}, + }, + ResourceAttributes: ResourceAttributesConfig{ + K8sDeploymentName: ResourceAttributeConfig{Enabled: false}, + K8sDeploymentUID: ResourceAttributeConfig{Enabled: false}, + K8sNamespaceName: ResourceAttributeConfig{Enabled: false}, + OpencensusResourcetype: ResourceAttributeConfig{Enabled: false}, + }, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cfg := loadMetricsBuilderConfig(t, tt.name) + if diff := cmp.Diff(tt.want, cfg, cmpopts.IgnoreUnexported(MetricConfig{}, ResourceAttributeConfig{})); diff != "" { + t.Errorf("Config mismatch (-expected +actual):\n%s", diff) + } + }) + } +} + +func loadMetricsBuilderConfig(t *testing.T, name string) MetricsBuilderConfig { + cm, err := confmaptest.LoadConf(filepath.Join("testdata", "config.yaml")) + require.NoError(t, err) + sub, err := cm.Sub(name) + require.NoError(t, err) + cfg := DefaultMetricsBuilderConfig() + require.NoError(t, component.UnmarshalConfig(sub, &cfg)) + return cfg +} diff --git a/receiver/k8sclusterreceiver/internal/deployment/internal/metadata/generated_metrics.go b/receiver/k8sclusterreceiver/internal/deployment/internal/metadata/generated_metrics.go new file mode 100644 index 000000000000..5f6c8c27ebce --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/deployment/internal/metadata/generated_metrics.go @@ -0,0 +1,272 @@ +// Code generated by mdatagen. DO NOT EDIT. + +package metadata + +import ( + "time" + + "go.opentelemetry.io/collector/component" + "go.opentelemetry.io/collector/pdata/pcommon" + "go.opentelemetry.io/collector/pdata/pmetric" + "go.opentelemetry.io/collector/receiver" + conventions "go.opentelemetry.io/collector/semconv/v1.18.0" +) + +type metricK8sDeploymentAvailable struct { + data pmetric.Metric // data buffer for generated metric. + config MetricConfig // metric config provided by user. + capacity int // max observed number of data points added to the metric. +} + +// init fills k8s.deployment.available metric with initial data. +func (m *metricK8sDeploymentAvailable) init() { + m.data.SetName("k8s.deployment.available") + m.data.SetDescription("Total number of available pods (ready for at least minReadySeconds) targeted by this deployment") + m.data.SetUnit("1") + m.data.SetEmptyGauge() +} + +func (m *metricK8sDeploymentAvailable) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val int64) { + if !m.config.Enabled { + return + } + dp := m.data.Gauge().DataPoints().AppendEmpty() + dp.SetStartTimestamp(start) + dp.SetTimestamp(ts) + dp.SetIntValue(val) +} + +// updateCapacity saves max length of data point slices that will be used for the slice capacity. +func (m *metricK8sDeploymentAvailable) updateCapacity() { + if m.data.Gauge().DataPoints().Len() > m.capacity { + m.capacity = m.data.Gauge().DataPoints().Len() + } +} + +// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points. +func (m *metricK8sDeploymentAvailable) emit(metrics pmetric.MetricSlice) { + if m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 { + m.updateCapacity() + m.data.MoveTo(metrics.AppendEmpty()) + m.init() + } +} + +func newMetricK8sDeploymentAvailable(cfg MetricConfig) metricK8sDeploymentAvailable { + m := metricK8sDeploymentAvailable{config: cfg} + if cfg.Enabled { + m.data = pmetric.NewMetric() + m.init() + } + return m +} + +type metricK8sDeploymentDesired struct { + data pmetric.Metric // data buffer for generated metric. + config MetricConfig // metric config provided by user. + capacity int // max observed number of data points added to the metric. +} + +// init fills k8s.deployment.desired metric with initial data. +func (m *metricK8sDeploymentDesired) init() { + m.data.SetName("k8s.deployment.desired") + m.data.SetDescription("Number of desired pods in this deployment") + m.data.SetUnit("1") + m.data.SetEmptyGauge() +} + +func (m *metricK8sDeploymentDesired) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val int64) { + if !m.config.Enabled { + return + } + dp := m.data.Gauge().DataPoints().AppendEmpty() + dp.SetStartTimestamp(start) + dp.SetTimestamp(ts) + dp.SetIntValue(val) +} + +// updateCapacity saves max length of data point slices that will be used for the slice capacity. +func (m *metricK8sDeploymentDesired) updateCapacity() { + if m.data.Gauge().DataPoints().Len() > m.capacity { + m.capacity = m.data.Gauge().DataPoints().Len() + } +} + +// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points. +func (m *metricK8sDeploymentDesired) emit(metrics pmetric.MetricSlice) { + if m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 { + m.updateCapacity() + m.data.MoveTo(metrics.AppendEmpty()) + m.init() + } +} + +func newMetricK8sDeploymentDesired(cfg MetricConfig) metricK8sDeploymentDesired { + m := metricK8sDeploymentDesired{config: cfg} + if cfg.Enabled { + m.data = pmetric.NewMetric() + m.init() + } + return m +} + +// MetricsBuilder provides an interface for scrapers to report metrics while taking care of all the transformations +// required to produce metric representation defined in metadata and user config. +type MetricsBuilder struct { + startTime pcommon.Timestamp // start time that will be applied to all recorded data points. + metricsCapacity int // maximum observed number of metrics per resource. + resourceCapacity int // maximum observed number of resource attributes. + metricsBuffer pmetric.Metrics // accumulates metrics data before emitting. + buildInfo component.BuildInfo // contains version information + resourceAttributesConfig ResourceAttributesConfig + metricK8sDeploymentAvailable metricK8sDeploymentAvailable + metricK8sDeploymentDesired metricK8sDeploymentDesired +} + +// metricBuilderOption applies changes to default metrics builder. +type metricBuilderOption func(*MetricsBuilder) + +// WithStartTime sets startTime on the metrics builder. +func WithStartTime(startTime pcommon.Timestamp) metricBuilderOption { + return func(mb *MetricsBuilder) { + mb.startTime = startTime + } +} + +func NewMetricsBuilder(mbc MetricsBuilderConfig, settings receiver.CreateSettings, options ...metricBuilderOption) *MetricsBuilder { + mb := &MetricsBuilder{ + startTime: pcommon.NewTimestampFromTime(time.Now()), + metricsBuffer: pmetric.NewMetrics(), + buildInfo: settings.BuildInfo, + resourceAttributesConfig: mbc.ResourceAttributes, + metricK8sDeploymentAvailable: newMetricK8sDeploymentAvailable(mbc.Metrics.K8sDeploymentAvailable), + metricK8sDeploymentDesired: newMetricK8sDeploymentDesired(mbc.Metrics.K8sDeploymentDesired), + } + for _, op := range options { + op(mb) + } + return mb +} + +// updateCapacity updates max length of metrics and resource attributes that will be used for the slice capacity. +func (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) { + if mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() { + mb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len() + } + if mb.resourceCapacity < rm.Resource().Attributes().Len() { + mb.resourceCapacity = rm.Resource().Attributes().Len() + } +} + +// ResourceMetricsOption applies changes to provided resource metrics. +type ResourceMetricsOption func(ResourceAttributesConfig, pmetric.ResourceMetrics) + +// WithK8sDeploymentName sets provided value as "k8s.deployment.name" attribute for current resource. +func WithK8sDeploymentName(val string) ResourceMetricsOption { + return func(rac ResourceAttributesConfig, rm pmetric.ResourceMetrics) { + if rac.K8sDeploymentName.Enabled { + rm.Resource().Attributes().PutStr("k8s.deployment.name", val) + } + } +} + +// WithK8sDeploymentUID sets provided value as "k8s.deployment.uid" attribute for current resource. +func WithK8sDeploymentUID(val string) ResourceMetricsOption { + return func(rac ResourceAttributesConfig, rm pmetric.ResourceMetrics) { + if rac.K8sDeploymentUID.Enabled { + rm.Resource().Attributes().PutStr("k8s.deployment.uid", val) + } + } +} + +// WithK8sNamespaceName sets provided value as "k8s.namespace.name" attribute for current resource. +func WithK8sNamespaceName(val string) ResourceMetricsOption { + return func(rac ResourceAttributesConfig, rm pmetric.ResourceMetrics) { + if rac.K8sNamespaceName.Enabled { + rm.Resource().Attributes().PutStr("k8s.namespace.name", val) + } + } +} + +// WithOpencensusResourcetype sets provided value as "opencensus.resourcetype" attribute for current resource. +func WithOpencensusResourcetype(val string) ResourceMetricsOption { + return func(rac ResourceAttributesConfig, rm pmetric.ResourceMetrics) { + if rac.OpencensusResourcetype.Enabled { + rm.Resource().Attributes().PutStr("opencensus.resourcetype", val) + } + } +} + +// WithStartTimeOverride overrides start time for all the resource metrics data points. +// This option should be only used if different start time has to be set on metrics coming from different resources. +func WithStartTimeOverride(start pcommon.Timestamp) ResourceMetricsOption { + return func(_ ResourceAttributesConfig, rm pmetric.ResourceMetrics) { + var dps pmetric.NumberDataPointSlice + metrics := rm.ScopeMetrics().At(0).Metrics() + for i := 0; i < metrics.Len(); i++ { + switch metrics.At(i).Type() { + case pmetric.MetricTypeGauge: + dps = metrics.At(i).Gauge().DataPoints() + case pmetric.MetricTypeSum: + dps = metrics.At(i).Sum().DataPoints() + } + for j := 0; j < dps.Len(); j++ { + dps.At(j).SetStartTimestamp(start) + } + } + } +} + +// EmitForResource saves all the generated metrics under a new resource and updates the internal state to be ready for +// recording another set of data points as part of another resource. This function can be helpful when one scraper +// needs to emit metrics from several resources. Otherwise calling this function is not required, +// just `Emit` function can be called instead. +// Resource attributes should be provided as ResourceMetricsOption arguments. +func (mb *MetricsBuilder) EmitForResource(rmo ...ResourceMetricsOption) { + rm := pmetric.NewResourceMetrics() + rm.SetSchemaUrl(conventions.SchemaURL) + rm.Resource().Attributes().EnsureCapacity(mb.resourceCapacity) + ils := rm.ScopeMetrics().AppendEmpty() + ils.Scope().SetName("otelcol/k8sclusterreceiver") + ils.Scope().SetVersion(mb.buildInfo.Version) + ils.Metrics().EnsureCapacity(mb.metricsCapacity) + mb.metricK8sDeploymentAvailable.emit(ils.Metrics()) + mb.metricK8sDeploymentDesired.emit(ils.Metrics()) + + for _, op := range rmo { + op(mb.resourceAttributesConfig, rm) + } + if ils.Metrics().Len() > 0 { + mb.updateCapacity(rm) + rm.MoveTo(mb.metricsBuffer.ResourceMetrics().AppendEmpty()) + } +} + +// Emit returns all the metrics accumulated by the metrics builder and updates the internal state to be ready for +// recording another set of metrics. This function will be responsible for applying all the transformations required to +// produce metric representation defined in metadata and user config, e.g. delta or cumulative. +func (mb *MetricsBuilder) Emit(rmo ...ResourceMetricsOption) pmetric.Metrics { + mb.EmitForResource(rmo...) + metrics := mb.metricsBuffer + mb.metricsBuffer = pmetric.NewMetrics() + return metrics +} + +// RecordK8sDeploymentAvailableDataPoint adds a data point to k8s.deployment.available metric. +func (mb *MetricsBuilder) RecordK8sDeploymentAvailableDataPoint(ts pcommon.Timestamp, val int64) { + mb.metricK8sDeploymentAvailable.recordDataPoint(mb.startTime, ts, val) +} + +// RecordK8sDeploymentDesiredDataPoint adds a data point to k8s.deployment.desired metric. +func (mb *MetricsBuilder) RecordK8sDeploymentDesiredDataPoint(ts pcommon.Timestamp, val int64) { + mb.metricK8sDeploymentDesired.recordDataPoint(mb.startTime, ts, val) +} + +// Reset resets metrics builder to its initial state. It should be used when external metrics source is restarted, +// and metrics builder should update its startTime and reset it's internal state accordingly. +func (mb *MetricsBuilder) Reset(options ...metricBuilderOption) { + mb.startTime = pcommon.NewTimestampFromTime(time.Now()) + for _, op := range options { + op(mb) + } +} diff --git a/receiver/k8sclusterreceiver/internal/deployment/internal/metadata/generated_metrics_test.go b/receiver/k8sclusterreceiver/internal/deployment/internal/metadata/generated_metrics_test.go new file mode 100644 index 000000000000..d80b78ae8de6 --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/deployment/internal/metadata/generated_metrics_test.go @@ -0,0 +1,146 @@ +// Code generated by mdatagen. DO NOT EDIT. + +package metadata + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "go.opentelemetry.io/collector/pdata/pcommon" + "go.opentelemetry.io/collector/pdata/pmetric" + "go.opentelemetry.io/collector/receiver/receivertest" + "go.uber.org/zap" + "go.uber.org/zap/zaptest/observer" +) + +type testConfigCollection int + +const ( + testSetDefault testConfigCollection = iota + testSetAll + testSetNone +) + +func TestMetricsBuilder(t *testing.T) { + tests := []struct { + name string + configSet testConfigCollection + }{ + { + name: "default", + configSet: testSetDefault, + }, + { + name: "all_set", + configSet: testSetAll, + }, + { + name: "none_set", + configSet: testSetNone, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + start := pcommon.Timestamp(1_000_000_000) + ts := pcommon.Timestamp(1_000_001_000) + observedZapCore, observedLogs := observer.New(zap.WarnLevel) + settings := receivertest.NewNopCreateSettings() + settings.Logger = zap.New(observedZapCore) + mb := NewMetricsBuilder(loadMetricsBuilderConfig(t, test.name), settings, WithStartTime(start)) + + expectedWarnings := 0 + assert.Equal(t, expectedWarnings, observedLogs.Len()) + + defaultMetricsCount := 0 + allMetricsCount := 0 + + defaultMetricsCount++ + allMetricsCount++ + mb.RecordK8sDeploymentAvailableDataPoint(ts, 1) + + defaultMetricsCount++ + allMetricsCount++ + mb.RecordK8sDeploymentDesiredDataPoint(ts, 1) + + metrics := mb.Emit(WithK8sDeploymentName("attr-val"), WithK8sDeploymentUID("attr-val"), WithK8sNamespaceName("attr-val"), WithOpencensusResourcetype("attr-val")) + + if test.configSet == testSetNone { + assert.Equal(t, 0, metrics.ResourceMetrics().Len()) + return + } + + assert.Equal(t, 1, metrics.ResourceMetrics().Len()) + rm := metrics.ResourceMetrics().At(0) + attrCount := 0 + enabledAttrCount := 0 + attrVal, ok := rm.Resource().Attributes().Get("k8s.deployment.name") + attrCount++ + assert.Equal(t, mb.resourceAttributesConfig.K8sDeploymentName.Enabled, ok) + if mb.resourceAttributesConfig.K8sDeploymentName.Enabled { + enabledAttrCount++ + assert.EqualValues(t, "attr-val", attrVal.Str()) + } + attrVal, ok = rm.Resource().Attributes().Get("k8s.deployment.uid") + attrCount++ + assert.Equal(t, mb.resourceAttributesConfig.K8sDeploymentUID.Enabled, ok) + if mb.resourceAttributesConfig.K8sDeploymentUID.Enabled { + enabledAttrCount++ + assert.EqualValues(t, "attr-val", attrVal.Str()) + } + attrVal, ok = rm.Resource().Attributes().Get("k8s.namespace.name") + attrCount++ + assert.Equal(t, mb.resourceAttributesConfig.K8sNamespaceName.Enabled, ok) + if mb.resourceAttributesConfig.K8sNamespaceName.Enabled { + enabledAttrCount++ + assert.EqualValues(t, "attr-val", attrVal.Str()) + } + attrVal, ok = rm.Resource().Attributes().Get("opencensus.resourcetype") + attrCount++ + assert.Equal(t, mb.resourceAttributesConfig.OpencensusResourcetype.Enabled, ok) + if mb.resourceAttributesConfig.OpencensusResourcetype.Enabled { + enabledAttrCount++ + assert.EqualValues(t, "attr-val", attrVal.Str()) + } + assert.Equal(t, enabledAttrCount, rm.Resource().Attributes().Len()) + assert.Equal(t, attrCount, 4) + + assert.Equal(t, 1, rm.ScopeMetrics().Len()) + ms := rm.ScopeMetrics().At(0).Metrics() + if test.configSet == testSetDefault { + assert.Equal(t, defaultMetricsCount, ms.Len()) + } + if test.configSet == testSetAll { + assert.Equal(t, allMetricsCount, ms.Len()) + } + validatedMetrics := make(map[string]bool) + for i := 0; i < ms.Len(); i++ { + switch ms.At(i).Name() { + case "k8s.deployment.available": + assert.False(t, validatedMetrics["k8s.deployment.available"], "Found a duplicate in the metrics slice: k8s.deployment.available") + validatedMetrics["k8s.deployment.available"] = true + assert.Equal(t, pmetric.MetricTypeGauge, ms.At(i).Type()) + assert.Equal(t, 1, ms.At(i).Gauge().DataPoints().Len()) + assert.Equal(t, "Total number of available pods (ready for at least minReadySeconds) targeted by this deployment", ms.At(i).Description()) + assert.Equal(t, "1", ms.At(i).Unit()) + dp := ms.At(i).Gauge().DataPoints().At(0) + assert.Equal(t, start, dp.StartTimestamp()) + assert.Equal(t, ts, dp.Timestamp()) + assert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType()) + assert.Equal(t, int64(1), dp.IntValue()) + case "k8s.deployment.desired": + assert.False(t, validatedMetrics["k8s.deployment.desired"], "Found a duplicate in the metrics slice: k8s.deployment.desired") + validatedMetrics["k8s.deployment.desired"] = true + assert.Equal(t, pmetric.MetricTypeGauge, ms.At(i).Type()) + assert.Equal(t, 1, ms.At(i).Gauge().DataPoints().Len()) + assert.Equal(t, "Number of desired pods in this deployment", ms.At(i).Description()) + assert.Equal(t, "1", ms.At(i).Unit()) + dp := ms.At(i).Gauge().DataPoints().At(0) + assert.Equal(t, start, dp.StartTimestamp()) + assert.Equal(t, ts, dp.Timestamp()) + assert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType()) + assert.Equal(t, int64(1), dp.IntValue()) + } + } + }) + } +} diff --git a/receiver/k8sclusterreceiver/internal/deployment/internal/metadata/testdata/config.yaml b/receiver/k8sclusterreceiver/internal/deployment/internal/metadata/testdata/config.yaml new file mode 100644 index 000000000000..0586c11988f5 --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/deployment/internal/metadata/testdata/config.yaml @@ -0,0 +1,31 @@ +default: +all_set: + metrics: + k8s.deployment.available: + enabled: true + k8s.deployment.desired: + enabled: true + resource_attributes: + k8s.deployment.name: + enabled: true + k8s.deployment.uid: + enabled: true + k8s.namespace.name: + enabled: true + opencensus.resourcetype: + enabled: true +none_set: + metrics: + k8s.deployment.available: + enabled: false + k8s.deployment.desired: + enabled: false + resource_attributes: + k8s.deployment.name: + enabled: false + k8s.deployment.uid: + enabled: false + k8s.namespace.name: + enabled: false + opencensus.resourcetype: + enabled: false diff --git a/receiver/k8sclusterreceiver/internal/deployment/metadata.yaml b/receiver/k8sclusterreceiver/internal/deployment/metadata.yaml new file mode 100644 index 000000000000..96b7e076fc1c --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/deployment/metadata.yaml @@ -0,0 +1,39 @@ +type: k8s/deployment + +sem_conv_version: 1.18.0 + +resource_attributes: + k8s.deployment.uid: + description: The UID of the Deployment. + type: string + enabled: true + + k8s.deployment.name: + description: The name of the Deployment. + type: string + enabled: true + + k8s.namespace.name: + description: The name of the namespace that the pod is running in. + type: string + enabled: true + + opencensus.resourcetype: + description: The OpenCensus resource type. + type: string + enabled: true + +metrics: + k8s.deployment.desired: + enabled: true + description: Number of desired pods in this deployment + unit: 1 + gauge: + value_type: int + + k8s.deployment.available: + enabled: true + description: Total number of available pods (ready for at least minReadySeconds) targeted by this deployment + unit: 1 + gauge: + value_type: int diff --git a/receiver/k8sclusterreceiver/internal/deployment/testdata/expected.yaml b/receiver/k8sclusterreceiver/internal/deployment/testdata/expected.yaml new file mode 100644 index 000000000000..5426fda52d1e --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/deployment/testdata/expected.yaml @@ -0,0 +1,37 @@ +resourceMetrics: + - resource: + attributes: + - key: k8s.deployment.name + value: + stringValue: test-deployment-1 + - key: k8s.deployment.uid + value: + stringValue: test-deployment-1-uid + - key: k8s.namespace.name + value: + stringValue: test-namespace + - key: opencensus.resourcetype + value: + stringValue: k8s + schemaUrl: "https://opentelemetry.io/schemas/1.18.0" + scopeMetrics: + - metrics: + - description: Total number of available pods (ready for at least minReadySeconds) targeted by this deployment + gauge: + dataPoints: + - asInt: "3" + startTimeUnixNano: "1686869619745174000" + timeUnixNano: "1686869619745178000" + name: k8s.deployment.available + unit: "1" + - description: Number of desired pods in this deployment + gauge: + dataPoints: + - asInt: "10" + startTimeUnixNano: "1686869619745174000" + timeUnixNano: "1686869619745178000" + name: k8s.deployment.desired + unit: "1" + scope: + name: otelcol/k8sclusterreceiver + version: latest diff --git a/receiver/k8sclusterreceiver/testdata/e2e/expected.yaml b/receiver/k8sclusterreceiver/testdata/e2e/expected.yaml index 2473234035cd..075b920861b2 100644 --- a/receiver/k8sclusterreceiver/testdata/e2e/expected.yaml +++ b/receiver/k8sclusterreceiver/testdata/e2e/expected.yaml @@ -223,6 +223,7 @@ resourceMetrics: - key: opencensus.resourcetype value: stringValue: k8s + schemaUrl: "https://opentelemetry.io/schemas/1.18.0" scopeMetrics: - metrics: - description: Number of desired pods in this deployment @@ -239,7 +240,9 @@ resourceMetrics: timeUnixNano: "1686772769034865545" name: k8s.deployment.available unit: "1" - scope: {} + scope: + name: otelcol/k8sclusterreceiver + version: latest - resource: attributes: - key: k8s.deployment.name @@ -254,6 +257,7 @@ resourceMetrics: - key: opencensus.resourcetype value: stringValue: k8s + schemaUrl: "https://opentelemetry.io/schemas/1.18.0" scopeMetrics: - metrics: - description: Number of desired pods in this deployment @@ -270,7 +274,9 @@ resourceMetrics: timeUnixNano: "1686772769034865545" name: k8s.deployment.available unit: "1" - scope: {} + scope: + name: otelcol/k8sclusterreceiver + version: latest - resource: attributes: - key: k8s.deployment.name @@ -285,6 +291,7 @@ resourceMetrics: - key: opencensus.resourcetype value: stringValue: k8s + schemaUrl: "https://opentelemetry.io/schemas/1.18.0" scopeMetrics: - metrics: - description: Number of desired pods in this deployment @@ -301,7 +308,9 @@ resourceMetrics: timeUnixNano: "1686772769034865545" name: k8s.deployment.available unit: "1" - scope: {} + scope: + name: otelcol/k8sclusterreceiver + version: latest - resource: attributes: - key: k8s.namespace.name