From 3eea808d7ee68584e8599a3dc53bce4f4fb1b42e Mon Sep 17 00:00:00 2001 From: Povilas Versockas Date: Mon, 17 Jul 2023 23:23:08 +0300 Subject: [PATCH] [receiver/k8scluster] Change k8s.replicationcontroller metrics to use mdatagen (#24268) --- ...luster-receiver-replicationcontroller.yaml | 20 ++ .../internal/collection/collector.go | 2 +- .../internal/replicationcontroller/doc.go | 6 + .../replicationcontroller/documentation.md | 40 +++ .../internal/metadata/generated_config.go | 84 ++++++ .../metadata/generated_config_test.go | 74 +++++ .../internal/metadata/generated_metrics.go | 272 ++++++++++++++++++ .../metadata/generated_metrics_test.go | 146 ++++++++++ .../internal/metadata/testdata/config.yaml | 31 ++ .../replicationcontroller/metadata.yaml | 40 +++ .../replicationcontrollers.go | 46 ++- .../replicationcontrollers_test.go | 49 ++++ .../testdata/expected.yaml | 33 +++ 13 files changed, 814 insertions(+), 29 deletions(-) create mode 100755 .chloggen/k8s-cluster-receiver-replicationcontroller.yaml create mode 100644 receiver/k8sclusterreceiver/internal/replicationcontroller/doc.go create mode 100644 receiver/k8sclusterreceiver/internal/replicationcontroller/documentation.md create mode 100644 receiver/k8sclusterreceiver/internal/replicationcontroller/internal/metadata/generated_config.go create mode 100644 receiver/k8sclusterreceiver/internal/replicationcontroller/internal/metadata/generated_config_test.go create mode 100644 receiver/k8sclusterreceiver/internal/replicationcontroller/internal/metadata/generated_metrics.go create mode 100644 receiver/k8sclusterreceiver/internal/replicationcontroller/internal/metadata/generated_metrics_test.go create mode 100644 receiver/k8sclusterreceiver/internal/replicationcontroller/internal/metadata/testdata/config.yaml create mode 100644 receiver/k8sclusterreceiver/internal/replicationcontroller/metadata.yaml create mode 100644 receiver/k8sclusterreceiver/internal/replicationcontroller/replicationcontrollers_test.go create mode 100644 receiver/k8sclusterreceiver/internal/replicationcontroller/testdata/expected.yaml diff --git a/.chloggen/k8s-cluster-receiver-replicationcontroller.yaml b/.chloggen/k8s-cluster-receiver-replicationcontroller.yaml new file mode 100755 index 000000000000..a4b242b18054 --- /dev/null +++ b/.chloggen/k8s-cluster-receiver-replicationcontroller.yaml @@ -0,0 +1,20 @@ +# Use this changelog template to create an entry for release notes. +# If your change doesn't affect end users, such as a test fix or a tooling change, +# you should instead start your pull request title with [chore] or use the "Skip Changelog" label. + +# 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: "Update k8s.replicationcontroller metrics to use mdatagen" + +# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists. +issues: [10553] + +# (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: diff --git a/receiver/k8sclusterreceiver/internal/collection/collector.go b/receiver/k8sclusterreceiver/internal/collection/collector.go index d4a8b3d4c72d..85f4bc188606 100644 --- a/receiver/k8sclusterreceiver/internal/collection/collector.go +++ b/receiver/k8sclusterreceiver/internal/collection/collector.go @@ -110,7 +110,7 @@ func (dc *DataCollector) SyncMetrics(obj interface{}) { case *corev1.Namespace: md = namespace.GetMetrics(dc.settings, o) case *corev1.ReplicationController: - md = ocsToMetrics(replicationcontroller.GetMetrics(o)) + md = replicationcontroller.GetMetrics(dc.settings, o) case *corev1.ResourceQuota: md = resourcequota.GetMetrics(dc.settings, o) case *appsv1.Deployment: diff --git a/receiver/k8sclusterreceiver/internal/replicationcontroller/doc.go b/receiver/k8sclusterreceiver/internal/replicationcontroller/doc.go new file mode 100644 index 000000000000..6d5af3f3f966 --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/replicationcontroller/doc.go @@ -0,0 +1,6 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +//go:generate mdatagen metadata.yaml + +package replicationcontroller // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/replicationcontroller" diff --git a/receiver/k8sclusterreceiver/internal/replicationcontroller/documentation.md b/receiver/k8sclusterreceiver/internal/replicationcontroller/documentation.md new file mode 100644 index 000000000000..61b12c6df21b --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/replicationcontroller/documentation.md @@ -0,0 +1,40 @@ +[comment]: <> (Code generated by mdatagen. DO NOT EDIT.) + +# k8s/replicationcontroller + +**Parent Component:** k8s_cluster + +## 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.replication_controller.available + +Total number of available pods (ready for at least minReadySeconds) targeted by this replication_controller + +| Unit | Metric Type | Value Type | +| ---- | ----------- | ---------- | +| 1 | Gauge | Int | + +### k8s.replication_controller.desired + +Number of desired pods in this replication_controller + +| Unit | Metric Type | Value Type | +| ---- | ----------- | ---------- | +| 1 | Gauge | Int | + +## Resource Attributes + +| Name | Description | Values | Enabled | +| ---- | ----------- | ------ | ------- | +| k8s.namespace.name | The k8s namespace name. | Any Str | true | +| k8s.replicationcontroller.name | The k8s replicationcontroller name. | Any Str | true | +| k8s.replicationcontroller.uid | The k8s replicationcontroller uid. | Any Str | true | +| opencensus.resourcetype | The OpenCensus resource type. | Any Str | true | diff --git a/receiver/k8sclusterreceiver/internal/replicationcontroller/internal/metadata/generated_config.go b/receiver/k8sclusterreceiver/internal/replicationcontroller/internal/metadata/generated_config.go new file mode 100644 index 000000000000..e8a34ac0a884 --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/replicationcontroller/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/replicationcontroller metrics. +type MetricsConfig struct { + K8sReplicationControllerAvailable MetricConfig `mapstructure:"k8s.replication_controller.available"` + K8sReplicationControllerDesired MetricConfig `mapstructure:"k8s.replication_controller.desired"` +} + +func DefaultMetricsConfig() MetricsConfig { + return MetricsConfig{ + K8sReplicationControllerAvailable: MetricConfig{ + Enabled: true, + }, + K8sReplicationControllerDesired: MetricConfig{ + Enabled: true, + }, + } +} + +// ResourceAttributeConfig provides common config for a particular resource attribute. +type ResourceAttributeConfig struct { + Enabled bool `mapstructure:"enabled"` +} + +// ResourceAttributesConfig provides config for k8s/replicationcontroller resource attributes. +type ResourceAttributesConfig struct { + K8sNamespaceName ResourceAttributeConfig `mapstructure:"k8s.namespace.name"` + K8sReplicationcontrollerName ResourceAttributeConfig `mapstructure:"k8s.replicationcontroller.name"` + K8sReplicationcontrollerUID ResourceAttributeConfig `mapstructure:"k8s.replicationcontroller.uid"` + OpencensusResourcetype ResourceAttributeConfig `mapstructure:"opencensus.resourcetype"` +} + +func DefaultResourceAttributesConfig() ResourceAttributesConfig { + return ResourceAttributesConfig{ + K8sNamespaceName: ResourceAttributeConfig{ + Enabled: true, + }, + K8sReplicationcontrollerName: ResourceAttributeConfig{ + Enabled: true, + }, + K8sReplicationcontrollerUID: ResourceAttributeConfig{ + Enabled: true, + }, + OpencensusResourcetype: ResourceAttributeConfig{ + Enabled: true, + }, + } +} + +// MetricsBuilderConfig is a configuration for k8s/replicationcontroller 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/replicationcontroller/internal/metadata/generated_config_test.go b/receiver/k8sclusterreceiver/internal/replicationcontroller/internal/metadata/generated_config_test.go new file mode 100644 index 000000000000..416031768f16 --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/replicationcontroller/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{ + K8sReplicationControllerAvailable: MetricConfig{Enabled: true}, + K8sReplicationControllerDesired: MetricConfig{Enabled: true}, + }, + ResourceAttributes: ResourceAttributesConfig{ + K8sNamespaceName: ResourceAttributeConfig{Enabled: true}, + K8sReplicationcontrollerName: ResourceAttributeConfig{Enabled: true}, + K8sReplicationcontrollerUID: ResourceAttributeConfig{Enabled: true}, + OpencensusResourcetype: ResourceAttributeConfig{Enabled: true}, + }, + }, + }, + { + name: "none_set", + want: MetricsBuilderConfig{ + Metrics: MetricsConfig{ + K8sReplicationControllerAvailable: MetricConfig{Enabled: false}, + K8sReplicationControllerDesired: MetricConfig{Enabled: false}, + }, + ResourceAttributes: ResourceAttributesConfig{ + K8sNamespaceName: ResourceAttributeConfig{Enabled: false}, + K8sReplicationcontrollerName: ResourceAttributeConfig{Enabled: false}, + K8sReplicationcontrollerUID: 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/replicationcontroller/internal/metadata/generated_metrics.go b/receiver/k8sclusterreceiver/internal/replicationcontroller/internal/metadata/generated_metrics.go new file mode 100644 index 000000000000..6b29b21b3842 --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/replicationcontroller/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 metricK8sReplicationControllerAvailable 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.replication_controller.available metric with initial data. +func (m *metricK8sReplicationControllerAvailable) init() { + m.data.SetName("k8s.replication_controller.available") + m.data.SetDescription("Total number of available pods (ready for at least minReadySeconds) targeted by this replication_controller") + m.data.SetUnit("1") + m.data.SetEmptyGauge() +} + +func (m *metricK8sReplicationControllerAvailable) 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 *metricK8sReplicationControllerAvailable) 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 *metricK8sReplicationControllerAvailable) emit(metrics pmetric.MetricSlice) { + if m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 { + m.updateCapacity() + m.data.MoveTo(metrics.AppendEmpty()) + m.init() + } +} + +func newMetricK8sReplicationControllerAvailable(cfg MetricConfig) metricK8sReplicationControllerAvailable { + m := metricK8sReplicationControllerAvailable{config: cfg} + if cfg.Enabled { + m.data = pmetric.NewMetric() + m.init() + } + return m +} + +type metricK8sReplicationControllerDesired 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.replication_controller.desired metric with initial data. +func (m *metricK8sReplicationControllerDesired) init() { + m.data.SetName("k8s.replication_controller.desired") + m.data.SetDescription("Number of desired pods in this replication_controller") + m.data.SetUnit("1") + m.data.SetEmptyGauge() +} + +func (m *metricK8sReplicationControllerDesired) 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 *metricK8sReplicationControllerDesired) 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 *metricK8sReplicationControllerDesired) emit(metrics pmetric.MetricSlice) { + if m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 { + m.updateCapacity() + m.data.MoveTo(metrics.AppendEmpty()) + m.init() + } +} + +func newMetricK8sReplicationControllerDesired(cfg MetricConfig) metricK8sReplicationControllerDesired { + m := metricK8sReplicationControllerDesired{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 + metricK8sReplicationControllerAvailable metricK8sReplicationControllerAvailable + metricK8sReplicationControllerDesired metricK8sReplicationControllerDesired +} + +// 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, + metricK8sReplicationControllerAvailable: newMetricK8sReplicationControllerAvailable(mbc.Metrics.K8sReplicationControllerAvailable), + metricK8sReplicationControllerDesired: newMetricK8sReplicationControllerDesired(mbc.Metrics.K8sReplicationControllerDesired), + } + 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) + +// 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) + } + } +} + +// WithK8sReplicationcontrollerName sets provided value as "k8s.replicationcontroller.name" attribute for current resource. +func WithK8sReplicationcontrollerName(val string) ResourceMetricsOption { + return func(rac ResourceAttributesConfig, rm pmetric.ResourceMetrics) { + if rac.K8sReplicationcontrollerName.Enabled { + rm.Resource().Attributes().PutStr("k8s.replicationcontroller.name", val) + } + } +} + +// WithK8sReplicationcontrollerUID sets provided value as "k8s.replicationcontroller.uid" attribute for current resource. +func WithK8sReplicationcontrollerUID(val string) ResourceMetricsOption { + return func(rac ResourceAttributesConfig, rm pmetric.ResourceMetrics) { + if rac.K8sReplicationcontrollerUID.Enabled { + rm.Resource().Attributes().PutStr("k8s.replicationcontroller.uid", 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.metricK8sReplicationControllerAvailable.emit(ils.Metrics()) + mb.metricK8sReplicationControllerDesired.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 +} + +// RecordK8sReplicationControllerAvailableDataPoint adds a data point to k8s.replication_controller.available metric. +func (mb *MetricsBuilder) RecordK8sReplicationControllerAvailableDataPoint(ts pcommon.Timestamp, val int64) { + mb.metricK8sReplicationControllerAvailable.recordDataPoint(mb.startTime, ts, val) +} + +// RecordK8sReplicationControllerDesiredDataPoint adds a data point to k8s.replication_controller.desired metric. +func (mb *MetricsBuilder) RecordK8sReplicationControllerDesiredDataPoint(ts pcommon.Timestamp, val int64) { + mb.metricK8sReplicationControllerDesired.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/replicationcontroller/internal/metadata/generated_metrics_test.go b/receiver/k8sclusterreceiver/internal/replicationcontroller/internal/metadata/generated_metrics_test.go new file mode 100644 index 000000000000..05c315d10eb2 --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/replicationcontroller/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.RecordK8sReplicationControllerAvailableDataPoint(ts, 1) + + defaultMetricsCount++ + allMetricsCount++ + mb.RecordK8sReplicationControllerDesiredDataPoint(ts, 1) + + metrics := mb.Emit(WithK8sNamespaceName("attr-val"), WithK8sReplicationcontrollerName("attr-val"), WithK8sReplicationcontrollerUID("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.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("k8s.replicationcontroller.name") + attrCount++ + assert.Equal(t, mb.resourceAttributesConfig.K8sReplicationcontrollerName.Enabled, ok) + if mb.resourceAttributesConfig.K8sReplicationcontrollerName.Enabled { + enabledAttrCount++ + assert.EqualValues(t, "attr-val", attrVal.Str()) + } + attrVal, ok = rm.Resource().Attributes().Get("k8s.replicationcontroller.uid") + attrCount++ + assert.Equal(t, mb.resourceAttributesConfig.K8sReplicationcontrollerUID.Enabled, ok) + if mb.resourceAttributesConfig.K8sReplicationcontrollerUID.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.replication_controller.available": + assert.False(t, validatedMetrics["k8s.replication_controller.available"], "Found a duplicate in the metrics slice: k8s.replication_controller.available") + validatedMetrics["k8s.replication_controller.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 replication_controller", 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.replication_controller.desired": + assert.False(t, validatedMetrics["k8s.replication_controller.desired"], "Found a duplicate in the metrics slice: k8s.replication_controller.desired") + validatedMetrics["k8s.replication_controller.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 replication_controller", 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/replicationcontroller/internal/metadata/testdata/config.yaml b/receiver/k8sclusterreceiver/internal/replicationcontroller/internal/metadata/testdata/config.yaml new file mode 100644 index 000000000000..33c0e5d3c0a8 --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/replicationcontroller/internal/metadata/testdata/config.yaml @@ -0,0 +1,31 @@ +default: +all_set: + metrics: + k8s.replication_controller.available: + enabled: true + k8s.replication_controller.desired: + enabled: true + resource_attributes: + k8s.namespace.name: + enabled: true + k8s.replicationcontroller.name: + enabled: true + k8s.replicationcontroller.uid: + enabled: true + opencensus.resourcetype: + enabled: true +none_set: + metrics: + k8s.replication_controller.available: + enabled: false + k8s.replication_controller.desired: + enabled: false + resource_attributes: + k8s.namespace.name: + enabled: false + k8s.replicationcontroller.name: + enabled: false + k8s.replicationcontroller.uid: + enabled: false + opencensus.resourcetype: + enabled: false diff --git a/receiver/k8sclusterreceiver/internal/replicationcontroller/metadata.yaml b/receiver/k8sclusterreceiver/internal/replicationcontroller/metadata.yaml new file mode 100644 index 000000000000..311e150fa85f --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/replicationcontroller/metadata.yaml @@ -0,0 +1,40 @@ +type: k8s/replicationcontroller + +sem_conv_version: 1.18.0 + +parent: k8s_cluster + +resource_attributes: + k8s.namespace.name: + description: The k8s namespace name. + type: string + enabled: true + + k8s.replicationcontroller.name: + description: The k8s replicationcontroller name. + type: string + enabled: true + + k8s.replicationcontroller.uid: + description: The k8s replicationcontroller uid. + type: string + enabled: true + + opencensus.resourcetype: + description: The OpenCensus resource type. + type: string + enabled: true + +metrics: + k8s.replication_controller.desired: + enabled: true + description: Number of desired pods in this replication_controller + unit: 1 + gauge: + value_type: int + k8s.replication_controller.available: + enabled: true + description: Total number of available pods (ready for at least minReadySeconds) targeted by this replication_controller + unit: 1 + gauge: + value_type: int diff --git a/receiver/k8sclusterreceiver/internal/replicationcontroller/replicationcontrollers.go b/receiver/k8sclusterreceiver/internal/replicationcontroller/replicationcontrollers.go index 7754152f7f74..8d297d55e53e 100644 --- a/receiver/k8sclusterreceiver/internal/replicationcontroller/replicationcontrollers.go +++ b/receiver/k8sclusterreceiver/internal/replicationcontroller/replicationcontrollers.go @@ -4,44 +4,34 @@ package replicationcontroller // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/replicationcontroller" import ( - agentmetricspb "github.com/census-instrumentation/opencensus-proto/gen-go/agent/metrics/v1" - resourcepb "github.com/census-instrumentation/opencensus-proto/gen-go/resource/v1" - conventions "go.opentelemetry.io/collector/semconv/v1.6.1" + "time" + + "go.opentelemetry.io/collector/pdata/pcommon" + "go.opentelemetry.io/collector/pdata/pmetric" + "go.opentelemetry.io/collector/receiver" corev1 "k8s.io/api/core/v1" "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/experimentalmetricmetadata" "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/constants" "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/metadata" - "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/replica" + imetadataphase "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/replicationcontroller/internal/metadata" ) -func GetMetrics(rc *corev1.ReplicationController) []*agentmetricspb.ExportMetricsServiceRequest { - if rc.Spec.Replicas == nil { - return nil - } +func GetMetrics(set receiver.CreateSettings, rc *corev1.ReplicationController) pmetric.Metrics { + mbphase := imetadataphase.NewMetricsBuilder(imetadataphase.DefaultMetricsBuilderConfig(), set) + ts := pcommon.NewTimestampFromTime(time.Now()) - return []*agentmetricspb.ExportMetricsServiceRequest{ - { - Resource: getResource(rc), - Metrics: replica.GetMetrics( - "replication_controller", - *rc.Spec.Replicas, - rc.Status.AvailableReplicas, - ), - }, + if rc.Spec.Replicas != nil { + mbphase.RecordK8sReplicationControllerDesiredDataPoint(ts, int64(*rc.Spec.Replicas)) + mbphase.RecordK8sReplicationControllerAvailableDataPoint(ts, int64(rc.Status.AvailableReplicas)) } -} - -func getResource(rc *corev1.ReplicationController) *resourcepb.Resource { - return &resourcepb.Resource{ - Type: constants.K8sType, - Labels: map[string]string{ - constants.K8sKeyReplicationControllerUID: string(rc.UID), - constants.K8sKeyReplicationControllerName: rc.Name, - conventions.AttributeK8SNamespaceName: rc.Namespace, - }, - } + return mbphase.Emit( + imetadataphase.WithK8sNamespaceName(rc.Namespace), + imetadataphase.WithK8sReplicationcontrollerName(rc.Name), + imetadataphase.WithK8sReplicationcontrollerUID(string(rc.UID)), + imetadataphase.WithOpencensusResourcetype("k8s"), + ) } func GetMetadata(rc *corev1.ReplicationController) map[experimentalmetricmetadata.ResourceID]*metadata.KubernetesMetadata { diff --git a/receiver/k8sclusterreceiver/internal/replicationcontroller/replicationcontrollers_test.go b/receiver/k8sclusterreceiver/internal/replicationcontroller/replicationcontrollers_test.go new file mode 100644 index 000000000000..f8e8dc0664a8 --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/replicationcontroller/replicationcontrollers_test.go @@ -0,0 +1,49 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +package replicationcontroller + +import ( + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" + "go.opentelemetry.io/collector/receiver/receivertest" + corev1 "k8s.io/api/core/v1" + v1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "github.com/open-telemetry/opentelemetry-collector-contrib/internal/coreinternal/golden" + "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/pdatatest/pmetrictest" +) + +func TestReplicationController(t *testing.T) { + + rc := &corev1.ReplicationController{ + ObjectMeta: v1.ObjectMeta{ + Name: "test-replicationcontroller-1", + Namespace: "test-namespace", + UID: "test-replicationcontroller-1-uid", + Labels: map[string]string{ + "app": "my-app", + "version": "v1", + }, + }, + Spec: corev1.ReplicationControllerSpec{ + Replicas: func() *int32 { i := int32(1); return &i }(), + }, + Status: corev1.ReplicationControllerStatus{AvailableReplicas: 2}, + } + + m := GetMetrics(receivertest.NewNopCreateSettings(), rc) + + expected, err := golden.ReadMetrics(filepath.Join("testdata", "expected.yaml")) + require.NoError(t, err) + require.NoError(t, pmetrictest.CompareMetrics(expected, m, + pmetrictest.IgnoreTimestamp(), + pmetrictest.IgnoreStartTimestamp(), + pmetrictest.IgnoreResourceMetricsOrder(), + pmetrictest.IgnoreMetricsOrder(), + pmetrictest.IgnoreScopeMetricsOrder(), + ), + ) +} diff --git a/receiver/k8sclusterreceiver/internal/replicationcontroller/testdata/expected.yaml b/receiver/k8sclusterreceiver/internal/replicationcontroller/testdata/expected.yaml new file mode 100644 index 000000000000..64df9eb4d7cf --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/replicationcontroller/testdata/expected.yaml @@ -0,0 +1,33 @@ +resourceMetrics: + - resource: + attributes: + - key: k8s.namespace.name + value: + stringValue: test-namespace + - key: k8s.replicationcontroller.name + value: + stringValue: test-replicationcontroller-1 + - key: k8s.replicationcontroller.uid + value: + stringValue: test-replicationcontroller-1-uid + - 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 replication_controller + gauge: + dataPoints: + - asInt: "2" + name: k8s.replication_controller.available + unit: "1" + - description: Number of desired pods in this replication_controller + gauge: + dataPoints: + - asInt: "1" + name: k8s.replication_controller.desired + unit: "1" + scope: + name: otelcol/k8sclusterreceiver + version: latest