Skip to content

[reciever/prometheusremotewritereceiver] Handle multiple timeseries with same metric name+type+unit #38453

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

Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions .chloggen/separate_timeseries_same_labels_same_datapoints.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Use this changelog template to create an entry for release notes.

# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'
change_type: enhancement

# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver)
component: prometheusremotewritereciever

# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`).
note: Add support for timeseries with the same labels and name/unitRef metric Metadata.

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

# (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: timeseries that has the same labels and name/unitRef metric Metadata should belongs to the same datapoints slice.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe too much details that doesn't add much value?


# If your change doesn't affect end users or the exported elements of any package,
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label.
# Optional: The change log or logs in which this entry should be included.
# e.g. '[user]' or '[user, api]'
# Include 'user' if the change is relevant to end users.
# Include 'api' if there is a change to a library API.
# Default: '[user]'
change_logs: [user]
113 changes: 68 additions & 45 deletions receiver/prometheusremotewritereceiver/receiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,11 +166,13 @@ func (prw *prometheusRemoteWriteReceiver) translateV2(_ context.Context, req *wr
// This cache is called "intra" because in the future we'll have a "interRequestCache" to cache resourceAttributes
// between requests based on the metric "target_info".
intraRequestCache = make(map[uint64]pmetric.ResourceMetrics)
// The key is composed by: resource_hash:scope_name:scope_version:metric_name:unit:type
// TODO: use the appropriate hash function.
metricCache = make(map[string]pmetric.Metric)
)

for _, ts := range req.Timeseries {
ls := ts.ToLabels(&labelsBuilder, req.Symbols)

if !ls.Has(labels.MetricName) {
badRequestErrors = errors.Join(badRequestErrors, fmt.Errorf("missing metric name in labels"))
continue
Expand All @@ -191,17 +193,75 @@ func (prw *prometheusRemoteWriteReceiver) translateV2(_ context.Context, req *wr
intraRequestCache[hashedLabels] = rm
}

scopeName, scopeVersion := prw.extractScopeInfo(ls)
metricName := ls.Get(labels.MetricName)
unit := ""
// TODO: Like UnitRef, we should assign the HelpRef to the metric.
if ts.Metadata.UnitRef > 0 && ts.Metadata.UnitRef < uint32(len(req.Symbols)) {
unit = req.Symbols[ts.Metadata.UnitRef]
}

// Temporary approach to generate the metric key.
// TODO: Replace this with a proper hashing function.
metricKey := fmt.Sprintf("%d:%s:%s:%s:%s:%d",
hashedLabels, // Resource identity
scopeName, // Scope name
scopeVersion, // Scope version
metricName, // Metric name
unit, // Unit
ts.Metadata.Type) // Metric type

var scope pmetric.ScopeMetrics
var foundScope bool
for i := 0; i < rm.ScopeMetrics().Len(); i++ {
s := rm.ScopeMetrics().At(i)
if s.Scope().Name() == scopeName && s.Scope().Version() == scopeVersion {
scope = s
foundScope = true
break
}
}
if !foundScope {
scope = rm.ScopeMetrics().AppendEmpty()
scope.Scope().SetName(scopeName)
scope.Scope().SetVersion(scopeVersion)
}

metric, exists := metricCache[metricKey]
// If the metric does not exist, we create an empty metric and add it to the cache.
if !exists {
metric = scope.Metrics().AppendEmpty()
metric.SetName(metricName)
metric.SetUnit(unit)

switch ts.Metadata.Type {
case writev2.Metadata_METRIC_TYPE_GAUGE:
metric.SetEmptyGauge()
case writev2.Metadata_METRIC_TYPE_COUNTER:
sum := metric.SetEmptySum()
sum.SetIsMonotonic(true)
sum.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)
case writev2.Metadata_METRIC_TYPE_HISTOGRAM:
metric.SetEmptyHistogram()
case writev2.Metadata_METRIC_TYPE_SUMMARY:
metric.SetEmptySummary()
}

metricCache[metricKey] = metric
}

// Otherwise, we append the samples to the existing metric.
switch ts.Metadata.Type {
case writev2.Metadata_METRIC_TYPE_COUNTER:
prw.addCounterDatapoints(rm, ls, ts)
case writev2.Metadata_METRIC_TYPE_GAUGE:
prw.addGaugeDatapoints(rm, ls, ts)
case writev2.Metadata_METRIC_TYPE_SUMMARY:
prw.addSummaryDatapoints(rm, ls, ts)
addDatapoints(metric.Gauge().DataPoints(), ls, ts)
case writev2.Metadata_METRIC_TYPE_COUNTER:
addDatapoints(metric.Sum().DataPoints(), ls, ts)
case writev2.Metadata_METRIC_TYPE_HISTOGRAM:
prw.addHistogramDatapoints(rm, ls, ts)
// TODO: Implement histogram to summary conversion
case writev2.Metadata_METRIC_TYPE_SUMMARY:
// TODO: Implement histogram to summary conversion
default:
badRequestErrors = errors.Join(badRequestErrors, fmt.Errorf("unsupported metric type %q for metric %q", ts.Metadata.Type, ls.Get(labels.MetricName)))
badRequestErrors = errors.Join(badRequestErrors, fmt.Errorf("unsupported metric type %q for metric %q", ts.Metadata.Type, metricName))
}
}

Expand All @@ -225,43 +285,6 @@ func parseJobAndInstance(dest pcommon.Map, job, instance string) {
}
}

func (prw *prometheusRemoteWriteReceiver) addCounterDatapoints(_ pmetric.ResourceMetrics, _ labels.Labels, _ writev2.TimeSeries) {
// TODO: Implement this function
}

func (prw *prometheusRemoteWriteReceiver) addGaugeDatapoints(rm pmetric.ResourceMetrics, ls labels.Labels, ts writev2.TimeSeries) {
// TODO: Cache metric name+type+unit and look up cache before creating new empty metric.
// In OTel name+type+unit is the unique identifier of a metric and we should not create
// a new metric if it already exists.

scopeName, scopeVersion := prw.extractScopeInfo(ls)

// Check if the name and version present in the labels are already present in the ResourceMetrics.
// If it is not present, we should create a new ScopeMetrics.
// Otherwise, we should append to the existing ScopeMetrics.
for j := 0; j < rm.ScopeMetrics().Len(); j++ {
scope := rm.ScopeMetrics().At(j)
if scopeName == scope.Scope().Name() && scopeVersion == scope.Scope().Version() {
addDatapoints(scope.Metrics().AppendEmpty().SetEmptyGauge().DataPoints(), ls, ts)
return
}
}

scope := rm.ScopeMetrics().AppendEmpty()
scope.Scope().SetName(scopeName)
scope.Scope().SetVersion(scopeVersion)
m := scope.Metrics().AppendEmpty().SetEmptyGauge()
addDatapoints(m.DataPoints(), ls, ts)
}

func (prw *prometheusRemoteWriteReceiver) addSummaryDatapoints(_ pmetric.ResourceMetrics, _ labels.Labels, _ writev2.TimeSeries) {
// TODO: Implement this function
}

func (prw *prometheusRemoteWriteReceiver) addHistogramDatapoints(_ pmetric.ResourceMetrics, _ labels.Labels, _ writev2.TimeSeries) {
// TODO: Implement this function
}

// addDatapoints adds the labels to the datapoints attributes.
// TODO: We're still not handling the StartTimestamp.
func addDatapoints(datapoints pmetric.NumberDataPointSlice, ls labels.Labels, ts writev2.TimeSeries) {
Expand Down
98 changes: 92 additions & 6 deletions receiver/prometheusremotewritereceiver/receiver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -175,13 +175,17 @@ func TestTranslateV2(t *testing.T) {
// Since we don't define the labels otel_scope_name and otel_scope_version, the default values coming from the receiver settings will be used.
sm1.Scope().SetName("OpenTelemetry Collector")
sm1.Scope().SetVersion("latest")
dp1 := sm1.Metrics().AppendEmpty().SetEmptyGauge().DataPoints().AppendEmpty()
metrics1 := sm1.Metrics().AppendEmpty()
metrics1.SetName("test_metric1")
metrics1.SetUnit("")

dp1 := metrics1.SetEmptyGauge().DataPoints().AppendEmpty()
dp1.SetTimestamp(pcommon.Timestamp(1 * int64(time.Millisecond)))
dp1.SetDoubleValue(1.0)
dp1.Attributes().PutStr("d", "e")
dp1.Attributes().PutStr("foo", "bar")

dp2 := sm1.Metrics().AppendEmpty().SetEmptyGauge().DataPoints().AppendEmpty()
dp2 := metrics1.Gauge().DataPoints().AppendEmpty()
dp2.SetTimestamp(pcommon.Timestamp(2 * int64(time.Millisecond)))
dp2.SetDoubleValue(2.0)
dp2.Attributes().PutStr("d", "e")
Expand All @@ -195,7 +199,11 @@ func TestTranslateV2(t *testing.T) {
sm2 := rm2.ScopeMetrics().AppendEmpty()
sm2.Scope().SetName("OpenTelemetry Collector")
sm2.Scope().SetVersion("latest")
dp3 := sm2.Metrics().AppendEmpty().SetEmptyGauge().DataPoints().AppendEmpty()
metrics2 := sm2.Metrics().AppendEmpty()
metrics2.SetName("test_metric1")
metrics2.SetUnit("")

dp3 := metrics2.SetEmptyGauge().DataPoints().AppendEmpty()
dp3.SetTimestamp(pcommon.Timestamp(2 * int64(time.Millisecond)))
dp3.SetDoubleValue(2.0)
dp3.Attributes().PutStr("d", "e")
Expand Down Expand Up @@ -249,22 +257,28 @@ func TestTranslateV2(t *testing.T) {
sm1 := rm1.ScopeMetrics().AppendEmpty()
sm1.Scope().SetName("scope1")
sm1.Scope().SetVersion("v1")
metrics1 := sm1.Metrics().AppendEmpty()
metrics1.SetName("test_metric")
metrics1.SetUnit("")

dp1 := sm1.Metrics().AppendEmpty().SetEmptyGauge().DataPoints().AppendEmpty()
dp1 := metrics1.SetEmptyGauge().DataPoints().AppendEmpty()
dp1.SetTimestamp(pcommon.Timestamp(1 * int64(time.Millisecond)))
dp1.SetDoubleValue(1.0)
dp1.Attributes().PutStr("d", "e")

dp2 := sm1.Metrics().AppendEmpty().SetEmptyGauge().DataPoints().AppendEmpty()
dp2 := metrics1.Gauge().DataPoints().AppendEmpty()
dp2.SetTimestamp(pcommon.Timestamp(2 * int64(time.Millisecond)))
dp2.SetDoubleValue(2.0)
dp2.Attributes().PutStr("d", "e")

sm2 := rm1.ScopeMetrics().AppendEmpty()
sm2.Scope().SetName("scope2")
sm2.Scope().SetVersion("v2")
metrics2 := sm2.Metrics().AppendEmpty()
metrics2.SetName("test_metric")
metrics2.SetUnit("")

dp3 := sm2.Metrics().AppendEmpty().SetEmptyGauge().DataPoints().AppendEmpty()
dp3 := metrics2.SetEmptyGauge().DataPoints().AppendEmpty()
dp3.SetTimestamp(pcommon.Timestamp(3 * int64(time.Millisecond)))
dp3.SetDoubleValue(3.0)
dp3.Attributes().PutStr("foo", "bar")
Expand All @@ -273,6 +287,78 @@ func TestTranslateV2(t *testing.T) {
}(),
expectedStats: remote.WriteResponseStats{},
},
{
name: "separate timeseries - same labels - should be same datapointslice",
request: &writev2.Request{
Symbols: []string{
"",
"__name__", "test_metric", // 1, 2
"job", "service-x/test", // 3, 4
"instance", "107cn001", // 5, 6
"otel_scope_name", "scope1", // 7, 8
"otel_scope_version", "v1", // 9, 10
"d", "e", // 11, 12
"foo", "bar", // 13, 14
"f", "g", // 15, 16
"seconds", "milliseconds", // 17, 18
},
Timeseries: []writev2.TimeSeries{
{
Metadata: writev2.Metadata{Type: writev2.Metadata_METRIC_TYPE_GAUGE, UnitRef: 17},
LabelsRefs: []uint32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
Samples: []writev2.Sample{{Value: 1, Timestamp: 1}},
},
{
Metadata: writev2.Metadata{Type: writev2.Metadata_METRIC_TYPE_GAUGE, UnitRef: 17},
LabelsRefs: []uint32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12},
Samples: []writev2.Sample{{Value: 2, Timestamp: 2}},
},
{
Metadata: writev2.Metadata{Type: writev2.Metadata_METRIC_TYPE_GAUGE, UnitRef: 18},
LabelsRefs: []uint32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13, 14},
Samples: []writev2.Sample{{Value: 3, Timestamp: 3}},
},
},
},
expectedMetrics: func() pmetric.Metrics {
expected := pmetric.NewMetrics()
rm1 := expected.ResourceMetrics().AppendEmpty()
rmAttributes1 := rm1.Resource().Attributes()
rmAttributes1.PutStr("service.namespace", "service-x")
rmAttributes1.PutStr("service.name", "test")
rmAttributes1.PutStr("service.instance.id", "107cn001")

sm1 := rm1.ScopeMetrics().AppendEmpty()
sm1.Scope().SetName("scope1")
sm1.Scope().SetVersion("v1")

// Expected to have 2 metrics and 3 data points.
// The first metric should have 2 data points.
// The second metric should have 1 data point.
metrics1 := sm1.Metrics().AppendEmpty()
metrics1.SetName("test_metric")
metrics1.SetUnit("seconds")
dp1 := metrics1.SetEmptyGauge().DataPoints().AppendEmpty()
dp1.SetTimestamp(pcommon.Timestamp(1 * int64(time.Millisecond)))
dp1.SetDoubleValue(1.0)
dp1.Attributes().PutStr("d", "e")

dp2 := metrics1.Gauge().DataPoints().AppendEmpty()
dp2.SetTimestamp(pcommon.Timestamp(2 * int64(time.Millisecond)))
dp2.SetDoubleValue(2.0)
dp2.Attributes().PutStr("d", "e")

metrics2 := sm1.Metrics().AppendEmpty()
metrics2.SetName("test_metric")
metrics2.SetUnit("milliseconds")
dp3 := metrics2.SetEmptyGauge().DataPoints().AppendEmpty()
dp3.SetTimestamp(pcommon.Timestamp(3 * int64(time.Millisecond)))
dp3.SetDoubleValue(3.0)
dp3.Attributes().PutStr("foo", "bar")

return expected
}(),
},
} {
t.Run(tc.name, func(t *testing.T) {
metrics, stats, err := prwReceiver.translateV2(ctx, tc.request)
Expand Down