Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Prometheus Receiver test for label_limit configuration #6150

Merged
61 changes: 49 additions & 12 deletions receiver/prometheusreceiver/metrics_receiver_helper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -467,20 +467,40 @@ func testComponent(t *testing.T, targets []*testData, useStartTimeMetric bool, s
metrics := cms.AllMetrics()

// split and store results by target name
pResults := make(map[string][]*pdata.ResourceMetrics)
for _, md := range metrics {
rms := md.ResourceMetrics()
for i := 0; i < rms.Len(); i++ {
name, _ := rms.At(i).Resource().Attributes().Get("service.name")
pResult, ok := pResults[name.AsString()]
if !ok {
pResult = make([]*pdata.ResourceMetrics, 0)
}
rm := rms.At(i)
pResults[name.AsString()] = append(pResult, &rm)
}
pResults := splitMetricsByTarget(metrics)
lres, lep := len(pResults), len(mp.endpoints)
assert.Equalf(t, lep, lres, "want %d targets, but got %v\n", lep, lres)

// loop to validate outputs for each targets
for _, target := range targets {
t.Run(target.name, func(t *testing.T) {
validScrapes := getValidScrapes(t, pResults[target.name])
target.validateFunc(t, target, validScrapes)
})
}
}

// starts prometheus receiver with custom config, retrieves metrics from MetricsSink
func testComponentCustomConfig(t *testing.T, targets []*testData, mp *mockPrometheus, cfg *promcfg.Config) {
ctx := context.Background()
defer mp.Close()

cms := new(consumertest.MetricsSink)
receiver := newPrometheusReceiver(componenttest.NewNopReceiverCreateSettings(), &Config{
ReceiverSettings: config.NewReceiverSettings(config.NewComponentID(typeStr)),
PrometheusConfig: cfg}, cms)

require.NoError(t, receiver.Start(ctx, componenttest.NewNopHost()))

// verify state after shutdown is called
t.Cleanup(func() { require.NoError(t, receiver.Shutdown(ctx)) })

// wait for all provided data to be scraped
mp.wg.Wait()
metrics := cms.AllMetrics()

// split and store results by target name
pResults := splitMetricsByTarget(metrics)
lres, lep := len(pResults), len(mp.endpoints)
assert.Equalf(t, lep, lres, "want %d targets, but got %v\n", lep, lres)

Expand All @@ -501,3 +521,20 @@ func flattenTargets(targets map[string][]*scrape.Target) []*scrape.Target {
}
return flatTargets
}

func splitMetricsByTarget(metrics []pdata.Metrics) map[string][]*pdata.ResourceMetrics {
pResults := make(map[string][]*pdata.ResourceMetrics)
for _, md := range metrics {
rms := md.ResourceMetrics()
for i := 0; i < rms.Len(); i++ {
name, _ := rms.At(i).Resource().Attributes().Get("service.name")
pResult, ok := pResults[name.AsString()]
if !ok {
pResult = make([]*pdata.ResourceMetrics, 0)
}
rm := rms.At(i)
pResults[name.AsString()] = append(pResult, &rm)
}
}
return pResults
}
142 changes: 142 additions & 0 deletions receiver/prometheusreceiver/metrics_receiver_labels_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package prometheusreceiver

import (
"testing"

"github.com/prometheus/prometheus/pkg/labels"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/collector/model/pdata"
)

const targetExternalLabels = `
# HELP go_threads Number of OS threads created
# TYPE go_threads gauge
go_threads 19`

func TestExternalLabels(t *testing.T) {
targets := []*testData{
{
name: "target1",
pages: []mockPrometheusResponse{
{code: 200, data: targetExternalLabels},
},
validateFunc: verifyExternalLabels,
},
}

mp, cfg, err := setupMockPrometheus(targets...)
cfg.GlobalConfig.ExternalLabels = labels.FromStrings("key", "value")
require.Nilf(t, err, "Failed to create Prometheus config: %v", err)

testComponentCustomConfig(t, targets, mp, cfg)
}

func verifyExternalLabels(t *testing.T, td *testData, rms []*pdata.ResourceMetrics) {
verifyNumScrapeResults(t, td, rms)
require.Greater(t, len(rms), 0, "At least one resource metric should be present")

wantAttributes := td.attributes
metrics1 := rms[0].InstrumentationLibraryMetrics().At(0).Metrics()
ts1 := metrics1.At(0).Gauge().DataPoints().At(0).Timestamp()
doCompare(t, "scrape-externalLabels", wantAttributes, rms[0], []testExpectation{
assertMetricPresent("go_threads",
compareMetricType(pdata.MetricDataTypeGauge),
[]dataPointExpectation{
{
numberPointComparator: []numberPointComparator{
compareTimestamp(ts1),
compareDoubleValue(19),
compareAttributes(map[string]string{"key": "value"}),
},
},
}),
})
}

const targetLabelLimit1 = `
# HELP test_gauge0 This is my gauge
# TYPE test_gauge0 gauge
test_gauge0{label1="value1",label2="value2"} 10
`

func verifyLabelLimitTarget1(t *testing.T, td *testData, rms []*pdata.ResourceMetrics) {
//each sample in the scraped metrics is within the configured label_limit, scrape should be successful
verifyNumScrapeResults(t, td, rms)
require.Greater(t, len(rms), 0, "At least one resource metric should be present")

want := td.attributes
metrics1 := rms[0].InstrumentationLibraryMetrics().At(0).Metrics()
ts1 := metrics1.At(0).Gauge().DataPoints().At(0).Timestamp()

doCompare(t, "scrape-labelLimit", want, rms[0], []testExpectation{
assertMetricPresent("test_gauge0",
compareMetricType(pdata.MetricDataTypeGauge),
[]dataPointExpectation{
{
numberPointComparator: []numberPointComparator{
compareTimestamp(ts1),
compareDoubleValue(10),
compareAttributes(map[string]string{"label1": "value1", "label2": "value2"}),
},
},
},
),
})
}

const targetLabelLimit2 = `
# HELP test_gauge0 This is my gauge
# TYPE test_gauge0 gauge
test_gauge0{label1="value1",label2="value2",label3="value3"} 10
`

func verifyLabelLimitTarget2(t *testing.T, _ *testData, rms []*pdata.ResourceMetrics) {
//Scrape should be unsuccessful since limit is exceeded in target2
for _, rm := range rms {
metrics := getMetrics(rm)
assertUp(t, 0, metrics)
}
}

func TestLabelLimitConfig(t *testing.T) {
targets := []*testData{
{
name: "target1",
pages: []mockPrometheusResponse{
{code: 200, data: targetLabelLimit1},
},
validateFunc: verifyLabelLimitTarget1,
},
{
name: "target2",
pages: []mockPrometheusResponse{
{code: 200, data: targetLabelLimit2},
},
validateFunc: verifyLabelLimitTarget2,
},
}

mp, cfg, err := setupMockPrometheus(targets...)
require.Nilf(t, err, "Failed to create Prometheus config: %v", err)

// set label limit in scrape_config
for _, scrapeCfg := range cfg.ScrapeConfigs {
scrapeCfg.LabelLimit = 5
}

testComponentCustomConfig(t, targets, mp, cfg)
}
108 changes: 0 additions & 108 deletions receiver/prometheusreceiver/metrics_reciever_external_labels_test.go

This file was deleted.