From 3f548bb6233e32f647d24bd758d567c11ad92ab5 Mon Sep 17 00:00:00 2001 From: Povilas Versockas Date: Mon, 17 Jul 2023 23:08:37 +0300 Subject: [PATCH] [receiver/k8scluster] Change k8s.cronjob.active_jobs to use mdatagen (#24057) **Description:** Change k8s.cronjob.active_jobs to use mdatagen **Link to tracking Issue:** https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/4367 --------- Co-authored-by: Dmitrii Anoshin --- .chloggen/k8s-cluster-receiver-cronjob.yaml | 20 ++ .../internal/collection/collector.go | 4 +- .../internal/cronjob/cronjobs.go | 89 ++----- .../internal/cronjob/cronjobs_test.go | 31 ++- .../internal/cronjob/doc.go | 6 + .../internal/cronjob/documentation.md | 33 +++ .../internal/metadata/generated_config.go | 84 +++++++ .../metadata/generated_config_test.go | 74 ++++++ .../internal/metadata/generated_metrics.go | 224 ++++++++++++++++++ .../metadata/generated_metrics_test.go | 137 +++++++++++ .../internal/metadata/testdata/config.yaml | 31 +++ .../internal/cronjob/metadata.yaml | 39 +++ .../internal/cronjob/testdata/expected.yaml | 27 +++ 13 files changed, 717 insertions(+), 82 deletions(-) create mode 100755 .chloggen/k8s-cluster-receiver-cronjob.yaml create mode 100644 receiver/k8sclusterreceiver/internal/cronjob/doc.go create mode 100644 receiver/k8sclusterreceiver/internal/cronjob/documentation.md create mode 100644 receiver/k8sclusterreceiver/internal/cronjob/internal/metadata/generated_config.go create mode 100644 receiver/k8sclusterreceiver/internal/cronjob/internal/metadata/generated_config_test.go create mode 100644 receiver/k8sclusterreceiver/internal/cronjob/internal/metadata/generated_metrics.go create mode 100644 receiver/k8sclusterreceiver/internal/cronjob/internal/metadata/generated_metrics_test.go create mode 100644 receiver/k8sclusterreceiver/internal/cronjob/internal/metadata/testdata/config.yaml create mode 100644 receiver/k8sclusterreceiver/internal/cronjob/metadata.yaml create mode 100644 receiver/k8sclusterreceiver/internal/cronjob/testdata/expected.yaml diff --git a/.chloggen/k8s-cluster-receiver-cronjob.yaml b/.chloggen/k8s-cluster-receiver-cronjob.yaml new file mode 100755 index 000000000000..7607f1057be7 --- /dev/null +++ b/.chloggen/k8s-cluster-receiver-cronjob.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: "Change k8s.cronjob.active_jobs 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 8739a66c3bfa..d4a8b3d4c72d 100644 --- a/receiver/k8sclusterreceiver/internal/collection/collector.go +++ b/receiver/k8sclusterreceiver/internal/collection/collector.go @@ -124,9 +124,9 @@ func (dc *DataCollector) SyncMetrics(obj interface{}) { case *batchv1.Job: md = jobs.GetMetrics(dc.settings, o) case *batchv1.CronJob: - md = ocsToMetrics(cronjob.GetMetrics(o)) + md = cronjob.GetMetrics(dc.settings, o) case *batchv1beta1.CronJob: - md = ocsToMetrics(cronjob.GetMetricsBeta(o)) + md = cronjob.GetMetricsBeta(dc.settings, o) case *autoscalingv2.HorizontalPodAutoscaler: md = hpa.GetMetrics(dc.settings, o) case *autoscalingv2beta2.HorizontalPodAutoscaler: diff --git a/receiver/k8sclusterreceiver/internal/cronjob/cronjobs.go b/receiver/k8sclusterreceiver/internal/cronjob/cronjobs.go index d0a9f6ca7b91..07b289a6ffa4 100644 --- a/receiver/k8sclusterreceiver/internal/cronjob/cronjobs.go +++ b/receiver/k8sclusterreceiver/internal/cronjob/cronjobs.go @@ -4,17 +4,18 @@ package cronjob // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/cronjob" import ( - agentmetricspb "github.com/census-instrumentation/opencensus-proto/gen-go/agent/metrics/v1" - metricspb "github.com/census-instrumentation/opencensus-proto/gen-go/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" batchv1 "k8s.io/api/batch/v1" batchv1beta1 "k8s.io/api/batch/v1beta1" "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/experimentalmetricmetadata" "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/constants" + imetadataphase "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/cronjob/internal/metadata" "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/metadata" - "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/utils" ) const ( @@ -23,71 +24,33 @@ const ( cronJobKeyConcurrencyPolicy = "concurrency_policy" ) -var activeJobs = &metricspb.MetricDescriptor{ - Name: "k8s.cronjob.active_jobs", - Description: "The number of actively running jobs for a cronjob", - Unit: "1", - Type: metricspb.MetricDescriptor_GAUGE_INT64, -} - -// TODO: All the CronJob related functions below can be de-duplicated using generics from go 1.19 +func GetMetrics(set receiver.CreateSettings, cj *batchv1.CronJob) pmetric.Metrics { + mbphase := imetadataphase.NewMetricsBuilder(imetadataphase.DefaultMetricsBuilderConfig(), set) + ts := pcommon.NewTimestampFromTime(time.Now()) -func GetMetrics(cj *batchv1.CronJob) []*agentmetricspb.ExportMetricsServiceRequest { - metrics := []*metricspb.Metric{ - { - MetricDescriptor: activeJobs, - Timeseries: []*metricspb.TimeSeries{ - utils.GetInt64TimeSeries(int64(len(cj.Status.Active))), - }, - }, - } + mbphase.RecordK8sCronjobActiveJobsDataPoint(ts, int64(len(cj.Status.Active))) - return []*agentmetricspb.ExportMetricsServiceRequest{ - { - Resource: getResourceForCronJob(cj), - Metrics: metrics, - }, - } + return mbphase.Emit( + imetadataphase.WithK8sNamespaceName(cj.Namespace), + imetadataphase.WithK8sCronjobUID(string(cj.UID)), + imetadataphase.WithK8sCronjobName(cj.Name), + imetadataphase.WithOpencensusResourcetype("k8s"), + ) } -func GetMetricsBeta(cj *batchv1beta1.CronJob) []*agentmetricspb.ExportMetricsServiceRequest { - metrics := []*metricspb.Metric{ - { - MetricDescriptor: activeJobs, - Timeseries: []*metricspb.TimeSeries{ - utils.GetInt64TimeSeries(int64(len(cj.Status.Active))), - }, - }, - } +func GetMetricsBeta(set receiver.CreateSettings, cj *batchv1beta1.CronJob) pmetric.Metrics { + mbphase := imetadataphase.NewMetricsBuilder(imetadataphase.DefaultMetricsBuilderConfig(), set) + ts := pcommon.NewTimestampFromTime(time.Now()) - return []*agentmetricspb.ExportMetricsServiceRequest{ - { - Resource: getResourceForCronJobBeta(cj), - Metrics: metrics, - }, - } -} + mbphase.RecordK8sCronjobActiveJobsDataPoint(ts, int64(len(cj.Status.Active))) -func getResourceForCronJob(cj *batchv1.CronJob) *resourcepb.Resource { - return &resourcepb.Resource{ - Type: constants.K8sType, - Labels: map[string]string{ - conventions.AttributeK8SCronJobUID: string(cj.UID), - conventions.AttributeK8SCronJobName: cj.Name, - conventions.AttributeK8SNamespaceName: cj.Namespace, - }, - } -} + return mbphase.Emit( + imetadataphase.WithK8sNamespaceName(cj.Namespace), + imetadataphase.WithK8sCronjobUID(string(cj.UID)), + imetadataphase.WithK8sCronjobName(cj.Name), + imetadataphase.WithOpencensusResourcetype("k8s"), + ) -func getResourceForCronJobBeta(cj *batchv1beta1.CronJob) *resourcepb.Resource { - return &resourcepb.Resource{ - Type: constants.K8sType, - Labels: map[string]string{ - conventions.AttributeK8SCronJobUID: string(cj.UID), - conventions.AttributeK8SCronJobName: cj.Name, - conventions.AttributeK8SNamespaceName: cj.Namespace, - }, - } } func GetMetadata(cj *batchv1.CronJob) map[experimentalmetricmetadata.ResourceID]*metadata.KubernetesMetadata { diff --git a/receiver/k8sclusterreceiver/internal/cronjob/cronjobs_test.go b/receiver/k8sclusterreceiver/internal/cronjob/cronjobs_test.go index 193921cc1362..e2ee226c0cdf 100644 --- a/receiver/k8sclusterreceiver/internal/cronjob/cronjobs_test.go +++ b/receiver/k8sclusterreceiver/internal/cronjob/cronjobs_test.go @@ -4,38 +4,35 @@ package cronjob import ( + "path/filepath" "testing" - metricspb "github.com/census-instrumentation/opencensus-proto/gen-go/metrics/v1" "github.com/stretchr/testify/require" + "go.opentelemetry.io/collector/receiver/receivertest" batchv1 "k8s.io/api/batch/v1" corev1 "k8s.io/api/core/v1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" - "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/metadata" - "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/testutils" ) func TestCronJobMetrics(t *testing.T) { cj := newCronJob("1") - actualResourceMetrics := GetMetrics(cj) - - require.Equal(t, 1, len(actualResourceMetrics)) - - require.Equal(t, 1, len(actualResourceMetrics[0].Metrics)) - testutils.AssertResource(t, actualResourceMetrics[0].Resource, constants.K8sType, - map[string]string{ - "k8s.cronjob.uid": "test-cronjob-1-uid", - "k8s.cronjob.name": "test-cronjob-1", - "k8s.namespace.name": "test-namespace", - }, + m := GetMetrics(receivertest.NewNopCreateSettings(), cj) + 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(), + ), ) - - testutils.AssertMetricsInt(t, actualResourceMetrics[0].Metrics[0], "k8s.cronjob.active_jobs", - metricspb.MetricDescriptor_GAUGE_INT64, 2) } func TestCronJobMetadata(t *testing.T) { diff --git a/receiver/k8sclusterreceiver/internal/cronjob/doc.go b/receiver/k8sclusterreceiver/internal/cronjob/doc.go new file mode 100644 index 000000000000..b7818998ef78 --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/cronjob/doc.go @@ -0,0 +1,6 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +//go:generate mdatagen metadata.yaml + +package cronjob // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/k8sclusterreceiver/internal/cronjob" diff --git a/receiver/k8sclusterreceiver/internal/cronjob/documentation.md b/receiver/k8sclusterreceiver/internal/cronjob/documentation.md new file mode 100644 index 000000000000..0f28efdb28ad --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/cronjob/documentation.md @@ -0,0 +1,33 @@ +[comment]: <> (Code generated by mdatagen. DO NOT EDIT.) + +# k8s/cronjob + +**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.cronjob.active_jobs + +The number of actively running jobs for a cronjob + +| Unit | Metric Type | Value Type | +| ---- | ----------- | ---------- | +| 1 | Gauge | Int | + +## Resource Attributes + +| Name | Description | Values | Enabled | +| ---- | ----------- | ------ | ------- | +| k8s.cronjob.name | The k8s CronJob name | Any Str | true | +| k8s.cronjob.uid | The k8s CronJob uid. | Any Str | true | +| k8s.namespace.name | The k8s namespace name | Any Str | true | +| k8s.node.name | The k8s node name | Any Str | true | +| opencensus.resourcetype | The OpenCensus resource type. | Any Str | true | diff --git a/receiver/k8sclusterreceiver/internal/cronjob/internal/metadata/generated_config.go b/receiver/k8sclusterreceiver/internal/cronjob/internal/metadata/generated_config.go new file mode 100644 index 000000000000..3b92995c2945 --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/cronjob/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/cronjob metrics. +type MetricsConfig struct { + K8sCronjobActiveJobs MetricConfig `mapstructure:"k8s.cronjob.active_jobs"` +} + +func DefaultMetricsConfig() MetricsConfig { + return MetricsConfig{ + K8sCronjobActiveJobs: MetricConfig{ + Enabled: true, + }, + } +} + +// ResourceAttributeConfig provides common config for a particular resource attribute. +type ResourceAttributeConfig struct { + Enabled bool `mapstructure:"enabled"` +} + +// ResourceAttributesConfig provides config for k8s/cronjob resource attributes. +type ResourceAttributesConfig struct { + K8sCronjobName ResourceAttributeConfig `mapstructure:"k8s.cronjob.name"` + K8sCronjobUID ResourceAttributeConfig `mapstructure:"k8s.cronjob.uid"` + K8sNamespaceName ResourceAttributeConfig `mapstructure:"k8s.namespace.name"` + K8sNodeName ResourceAttributeConfig `mapstructure:"k8s.node.name"` + OpencensusResourcetype ResourceAttributeConfig `mapstructure:"opencensus.resourcetype"` +} + +func DefaultResourceAttributesConfig() ResourceAttributesConfig { + return ResourceAttributesConfig{ + K8sCronjobName: ResourceAttributeConfig{ + Enabled: true, + }, + K8sCronjobUID: ResourceAttributeConfig{ + Enabled: true, + }, + K8sNamespaceName: ResourceAttributeConfig{ + Enabled: true, + }, + K8sNodeName: ResourceAttributeConfig{ + Enabled: true, + }, + OpencensusResourcetype: ResourceAttributeConfig{ + Enabled: true, + }, + } +} + +// MetricsBuilderConfig is a configuration for k8s/cronjob 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/cronjob/internal/metadata/generated_config_test.go b/receiver/k8sclusterreceiver/internal/cronjob/internal/metadata/generated_config_test.go new file mode 100644 index 000000000000..fa1c834077dc --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/cronjob/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{ + K8sCronjobActiveJobs: MetricConfig{Enabled: true}, + }, + ResourceAttributes: ResourceAttributesConfig{ + K8sCronjobName: ResourceAttributeConfig{Enabled: true}, + K8sCronjobUID: ResourceAttributeConfig{Enabled: true}, + K8sNamespaceName: ResourceAttributeConfig{Enabled: true}, + K8sNodeName: ResourceAttributeConfig{Enabled: true}, + OpencensusResourcetype: ResourceAttributeConfig{Enabled: true}, + }, + }, + }, + { + name: "none_set", + want: MetricsBuilderConfig{ + Metrics: MetricsConfig{ + K8sCronjobActiveJobs: MetricConfig{Enabled: false}, + }, + ResourceAttributes: ResourceAttributesConfig{ + K8sCronjobName: ResourceAttributeConfig{Enabled: false}, + K8sCronjobUID: ResourceAttributeConfig{Enabled: false}, + K8sNamespaceName: ResourceAttributeConfig{Enabled: false}, + K8sNodeName: 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/cronjob/internal/metadata/generated_metrics.go b/receiver/k8sclusterreceiver/internal/cronjob/internal/metadata/generated_metrics.go new file mode 100644 index 000000000000..80b96962e224 --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/cronjob/internal/metadata/generated_metrics.go @@ -0,0 +1,224 @@ +// 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 metricK8sCronjobActiveJobs 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.cronjob.active_jobs metric with initial data. +func (m *metricK8sCronjobActiveJobs) init() { + m.data.SetName("k8s.cronjob.active_jobs") + m.data.SetDescription("The number of actively running jobs for a cronjob") + m.data.SetUnit("1") + m.data.SetEmptyGauge() +} + +func (m *metricK8sCronjobActiveJobs) 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 *metricK8sCronjobActiveJobs) 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 *metricK8sCronjobActiveJobs) emit(metrics pmetric.MetricSlice) { + if m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 { + m.updateCapacity() + m.data.MoveTo(metrics.AppendEmpty()) + m.init() + } +} + +func newMetricK8sCronjobActiveJobs(cfg MetricConfig) metricK8sCronjobActiveJobs { + m := metricK8sCronjobActiveJobs{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 + metricK8sCronjobActiveJobs metricK8sCronjobActiveJobs +} + +// 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, + metricK8sCronjobActiveJobs: newMetricK8sCronjobActiveJobs(mbc.Metrics.K8sCronjobActiveJobs), + } + 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) + +// WithK8sCronjobName sets provided value as "k8s.cronjob.name" attribute for current resource. +func WithK8sCronjobName(val string) ResourceMetricsOption { + return func(rac ResourceAttributesConfig, rm pmetric.ResourceMetrics) { + if rac.K8sCronjobName.Enabled { + rm.Resource().Attributes().PutStr("k8s.cronjob.name", val) + } + } +} + +// WithK8sCronjobUID sets provided value as "k8s.cronjob.uid" attribute for current resource. +func WithK8sCronjobUID(val string) ResourceMetricsOption { + return func(rac ResourceAttributesConfig, rm pmetric.ResourceMetrics) { + if rac.K8sCronjobUID.Enabled { + rm.Resource().Attributes().PutStr("k8s.cronjob.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) + } + } +} + +// WithK8sNodeName sets provided value as "k8s.node.name" attribute for current resource. +func WithK8sNodeName(val string) ResourceMetricsOption { + return func(rac ResourceAttributesConfig, rm pmetric.ResourceMetrics) { + if rac.K8sNodeName.Enabled { + rm.Resource().Attributes().PutStr("k8s.node.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.metricK8sCronjobActiveJobs.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 +} + +// RecordK8sCronjobActiveJobsDataPoint adds a data point to k8s.cronjob.active_jobs metric. +func (mb *MetricsBuilder) RecordK8sCronjobActiveJobsDataPoint(ts pcommon.Timestamp, val int64) { + mb.metricK8sCronjobActiveJobs.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/cronjob/internal/metadata/generated_metrics_test.go b/receiver/k8sclusterreceiver/internal/cronjob/internal/metadata/generated_metrics_test.go new file mode 100644 index 000000000000..0e9e8f9c7fa9 --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/cronjob/internal/metadata/generated_metrics_test.go @@ -0,0 +1,137 @@ +// 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.RecordK8sCronjobActiveJobsDataPoint(ts, 1) + + metrics := mb.Emit(WithK8sCronjobName("attr-val"), WithK8sCronjobUID("attr-val"), WithK8sNamespaceName("attr-val"), WithK8sNodeName("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.cronjob.name") + attrCount++ + assert.Equal(t, mb.resourceAttributesConfig.K8sCronjobName.Enabled, ok) + if mb.resourceAttributesConfig.K8sCronjobName.Enabled { + enabledAttrCount++ + assert.EqualValues(t, "attr-val", attrVal.Str()) + } + attrVal, ok = rm.Resource().Attributes().Get("k8s.cronjob.uid") + attrCount++ + assert.Equal(t, mb.resourceAttributesConfig.K8sCronjobUID.Enabled, ok) + if mb.resourceAttributesConfig.K8sCronjobUID.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("k8s.node.name") + attrCount++ + assert.Equal(t, mb.resourceAttributesConfig.K8sNodeName.Enabled, ok) + if mb.resourceAttributesConfig.K8sNodeName.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, 5) + + 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.cronjob.active_jobs": + assert.False(t, validatedMetrics["k8s.cronjob.active_jobs"], "Found a duplicate in the metrics slice: k8s.cronjob.active_jobs") + validatedMetrics["k8s.cronjob.active_jobs"] = true + assert.Equal(t, pmetric.MetricTypeGauge, ms.At(i).Type()) + assert.Equal(t, 1, ms.At(i).Gauge().DataPoints().Len()) + assert.Equal(t, "The number of actively running jobs for a cronjob", 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/cronjob/internal/metadata/testdata/config.yaml b/receiver/k8sclusterreceiver/internal/cronjob/internal/metadata/testdata/config.yaml new file mode 100644 index 000000000000..da76e812bac8 --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/cronjob/internal/metadata/testdata/config.yaml @@ -0,0 +1,31 @@ +default: +all_set: + metrics: + k8s.cronjob.active_jobs: + enabled: true + resource_attributes: + k8s.cronjob.name: + enabled: true + k8s.cronjob.uid: + enabled: true + k8s.namespace.name: + enabled: true + k8s.node.name: + enabled: true + opencensus.resourcetype: + enabled: true +none_set: + metrics: + k8s.cronjob.active_jobs: + enabled: false + resource_attributes: + k8s.cronjob.name: + enabled: false + k8s.cronjob.uid: + enabled: false + k8s.namespace.name: + enabled: false + k8s.node.name: + enabled: false + opencensus.resourcetype: + enabled: false diff --git a/receiver/k8sclusterreceiver/internal/cronjob/metadata.yaml b/receiver/k8sclusterreceiver/internal/cronjob/metadata.yaml new file mode 100644 index 000000000000..38a038902154 --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/cronjob/metadata.yaml @@ -0,0 +1,39 @@ +type: k8s/cronjob + +sem_conv_version: 1.18.0 + +parent: k8s_cluster + +resource_attributes: + k8s.cronjob.uid: + description: The k8s CronJob uid. + type: string + enabled: true + + k8s.cronjob.name: + description: The k8s CronJob name + type: string + enabled: true + + k8s.namespace.name: + description: The k8s namespace name + type: string + enabled: true + + k8s.node.name: + description: The k8s node name + type: string + enabled: true + + opencensus.resourcetype: + description: The OpenCensus resource type. + type: string + enabled: true + +metrics: + k8s.cronjob.active_jobs: + enabled: true + description: The number of actively running jobs for a cronjob + unit: "1" + gauge: + value_type: int diff --git a/receiver/k8sclusterreceiver/internal/cronjob/testdata/expected.yaml b/receiver/k8sclusterreceiver/internal/cronjob/testdata/expected.yaml new file mode 100644 index 000000000000..cae91467060e --- /dev/null +++ b/receiver/k8sclusterreceiver/internal/cronjob/testdata/expected.yaml @@ -0,0 +1,27 @@ +resourceMetrics: + - resource: + attributes: + - key: k8s.namespace.name + value: + stringValue: test-namespace + - key: k8s.cronjob.name + value: + stringValue: test-cronjob-1 + - key: k8s.cronjob.uid + value: + stringValue: test-cronjob-1-uid + - key: opencensus.resourcetype + value: + stringValue: k8s + schemaUrl: https://opentelemetry.io/schemas/1.18.0 + scopeMetrics: + - metrics: + - description: The number of actively running jobs for a cronjob + gauge: + dataPoints: + - asInt: "2" + name: k8s.cronjob.active_jobs + unit: "1" + scope: + name: otelcol/k8sclusterreceiver + version: latest