Metrics: Use ReadOnlyTagCollection to encapsulate key/values on MetricPoint (#2642)

This commit is contained in:
Mikel Blanchard 2021-11-20 13:59:22 -08:00 committed by GitHub
parent 31a2d673da
commit 71f5fb00a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 177 additions and 71 deletions

View File

@ -80,16 +80,13 @@ namespace OpenTelemetry.Exporter
{
string valueDisplay = string.Empty;
StringBuilder tagsBuilder = new StringBuilder();
if (metricPoint.Keys != null)
foreach (var tag in metricPoint.Tags)
{
for (int i = 0; i < metricPoint.Keys.Length; i++)
{
tagsBuilder.Append(metricPoint.Keys[i]);
tagsBuilder.Append(tag.Key);
tagsBuilder.Append(':');
tagsBuilder.Append(metricPoint.Values[i]);
tagsBuilder.Append(tag.Value);
tagsBuilder.Append(' ');
}
}
var tags = tagsBuilder.ToString().TrimEnd();

View File

@ -156,7 +156,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
TimeUnixNano = (ulong)metricPoint.EndTime.ToUnixTimeNanoseconds(),
};
AddAttributes(metricPoint.Keys, metricPoint.Values, dataPoint.Attributes);
AddAttributes(metricPoint.Tags, dataPoint.Attributes);
dataPoint.AsInt = metricPoint.LongValue;
sum.DataPoints.Add(dataPoint);
@ -180,7 +180,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
TimeUnixNano = (ulong)metricPoint.EndTime.ToUnixTimeNanoseconds(),
};
AddAttributes(metricPoint.Keys, metricPoint.Values, dataPoint.Attributes);
AddAttributes(metricPoint.Tags, dataPoint.Attributes);
dataPoint.AsDouble = metricPoint.DoubleValue;
sum.DataPoints.Add(dataPoint);
@ -201,7 +201,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
TimeUnixNano = (ulong)metricPoint.EndTime.ToUnixTimeNanoseconds(),
};
AddAttributes(metricPoint.Keys, metricPoint.Values, dataPoint.Attributes);
AddAttributes(metricPoint.Tags, dataPoint.Attributes);
dataPoint.AsInt = metricPoint.LongValue;
gauge.DataPoints.Add(dataPoint);
@ -222,7 +222,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
TimeUnixNano = (ulong)metricPoint.EndTime.ToUnixTimeNanoseconds(),
};
AddAttributes(metricPoint.Keys, metricPoint.Values, dataPoint.Attributes);
AddAttributes(metricPoint.Tags, dataPoint.Attributes);
dataPoint.AsDouble = metricPoint.DoubleValue;
gauge.DataPoints.Add(dataPoint);
@ -245,7 +245,7 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
TimeUnixNano = (ulong)metricPoint.EndTime.ToUnixTimeNanoseconds(),
};
AddAttributes(metricPoint.Keys, metricPoint.Values, dataPoint.Attributes);
AddAttributes(metricPoint.Tags, dataPoint.Attributes);
dataPoint.Count = (ulong)metricPoint.LongValue;
dataPoint.Sum = metricPoint.DoubleValue;
@ -272,17 +272,13 @@ namespace OpenTelemetry.Exporter.OpenTelemetryProtocol.Implementation
return otlpMetric;
}
private static void AddAttributes(string[] keys, object[] values, RepeatedField<OtlpCommon.KeyValue> attributes)
private static void AddAttributes(ReadOnlyTagCollection tags, RepeatedField<OtlpCommon.KeyValue> attributes)
{
if (keys != null)
foreach (var tag in tags)
{
for (int i = 0; i < keys.Length; i++)
{
KeyValuePair<string, object> tag = new KeyValuePair<string, object>(keys[i], values[i]);
attributes.Add(tag.ToOtlpAttribute());
}
}
}
/*
[MethodImpl(MethodImplOptions.AggressiveInlining)]

View File

@ -39,25 +39,25 @@ namespace OpenTelemetry.Exporter.Prometheus
{
foreach (ref var metricPoint in metric.GetMetricPoints())
{
var keys = metricPoint.Keys;
var values = metricPoint.Values;
var tags = metricPoint.Tags;
var timestamp = metricPoint.EndTime.ToUnixTimeMilliseconds();
// Counter and Gauge
cursor = WriteMetricName(buffer, cursor, metric.Name, metric.Unit);
if (keys != null && keys.Length > 0)
if (tags.Count > 0)
{
buffer[cursor++] = unchecked((byte)'{');
for (var i = 0; i < keys.Length; i++)
int i = 0;
foreach (var tag in tags)
{
if (i > 0)
if (i++ > 0)
{
buffer[cursor++] = unchecked((byte)',');
}
cursor = WriteLabel(buffer, cursor, keys[i], values[i]);
cursor = WriteLabel(buffer, cursor, tag.Key, tag.Value);
}
buffer[cursor++] = unchecked((byte)'}');
@ -85,8 +85,7 @@ namespace OpenTelemetry.Exporter.Prometheus
{
foreach (ref var metricPoint in metric.GetMetricPoints())
{
var keys = metricPoint.Keys;
var values = metricPoint.Values;
var tags = metricPoint.Tags;
var timestamp = metricPoint.EndTime.ToUnixTimeMilliseconds();
// Histogram buckets
@ -100,14 +99,11 @@ namespace OpenTelemetry.Exporter.Prometheus
cursor = WriteMetricName(buffer, cursor, metric.Name, metric.Unit);
cursor = WriteAsciiStringNoEscape(buffer, cursor, "_bucket{");
if (keys != null)
foreach (var tag in tags)
{
for (var i = 0; i < keys.Length; i++)
{
cursor = WriteLabel(buffer, cursor, keys[i], values[i]);
cursor = WriteLabel(buffer, cursor, tag.Key, tag.Value);
buffer[cursor++] = unchecked((byte)',');
}
}
cursor = WriteAsciiStringNoEscape(buffer, cursor, "le=\"");
@ -134,18 +130,19 @@ namespace OpenTelemetry.Exporter.Prometheus
cursor = WriteMetricName(buffer, cursor, metric.Name, metric.Unit);
cursor = WriteAsciiStringNoEscape(buffer, cursor, "_sum");
if (keys != null && keys.Length > 0)
if (tags.Count > 0)
{
buffer[cursor++] = unchecked((byte)'{');
for (var i = 0; i < keys.Length; i++)
int i = 0;
foreach (var tag in tags)
{
if (i > 0)
if (i++ > 0)
{
buffer[cursor++] = unchecked((byte)',');
}
cursor = WriteLabel(buffer, cursor, keys[i], values[i]);
cursor = WriteLabel(buffer, cursor, tag.Key, tag.Value);
}
buffer[cursor++] = unchecked((byte)'}');
@ -164,18 +161,19 @@ namespace OpenTelemetry.Exporter.Prometheus
cursor = WriteMetricName(buffer, cursor, metric.Name, metric.Unit);
cursor = WriteAsciiStringNoEscape(buffer, cursor, "_count");
if (keys != null && keys.Length > 0)
if (tags.Count > 0)
{
buffer[cursor++] = unchecked((byte)'{');
for (var i = 0; i < keys.Length; i++)
int i = 0;
foreach (var tag in tags)
{
if (i > 0)
if (i++ > 0)
{
buffer[cursor++] = unchecked((byte)',');
}
cursor = WriteLabel(buffer, cursor, keys[i], values[i]);
cursor = WriteLabel(buffer, cursor, tag.Key, tag.Value);
}
buffer[cursor++] = unchecked((byte)'}');

View File

@ -60,11 +60,10 @@ OpenTelemetry.Metrics.MetricPoint.BucketCounts.get -> long[]
OpenTelemetry.Metrics.MetricPoint.DoubleValue.get -> double
OpenTelemetry.Metrics.MetricPoint.EndTime.get -> System.DateTimeOffset
OpenTelemetry.Metrics.MetricPoint.ExplicitBounds.get -> double[]
OpenTelemetry.Metrics.MetricPoint.Keys.get -> string[]
OpenTelemetry.Metrics.MetricPoint.LongValue.get -> long
OpenTelemetry.Metrics.MetricPoint.MetricPoint() -> void
OpenTelemetry.Metrics.MetricPoint.StartTime.get -> System.DateTimeOffset
OpenTelemetry.Metrics.MetricPoint.Values.get -> object[]
OpenTelemetry.Metrics.MetricPoint.Tags.get -> OpenTelemetry.ReadOnlyTagCollection
OpenTelemetry.Metrics.MetricReader
OpenTelemetry.Metrics.MetricReader.Collect(int timeoutMilliseconds = -1) -> bool
OpenTelemetry.Metrics.MetricReader.Dispose() -> void
@ -92,6 +91,14 @@ OpenTelemetry.Metrics.MetricType.LongSum = 26 -> OpenTelemetry.Metrics.MetricTyp
OpenTelemetry.Metrics.MetricTypeExtensions
OpenTelemetry.Metrics.PeriodicExportingMetricReader
OpenTelemetry.Metrics.PeriodicExportingMetricReader.PeriodicExportingMetricReader(OpenTelemetry.BaseExporter<OpenTelemetry.Metrics.Metric> exporter, int exportIntervalMilliseconds = 60000, int exportTimeoutMilliseconds = 30000) -> void
OpenTelemetry.ReadOnlyTagCollection
OpenTelemetry.ReadOnlyTagCollection.Count.get -> int
OpenTelemetry.ReadOnlyTagCollection.Enumerator
OpenTelemetry.ReadOnlyTagCollection.Enumerator.Current.get -> System.Collections.Generic.KeyValuePair<string, object>
OpenTelemetry.ReadOnlyTagCollection.Enumerator.Enumerator() -> void
OpenTelemetry.ReadOnlyTagCollection.Enumerator.MoveNext() -> bool
OpenTelemetry.ReadOnlyTagCollection.GetEnumerator() -> OpenTelemetry.ReadOnlyTagCollection.Enumerator
OpenTelemetry.ReadOnlyTagCollection.ReadOnlyTagCollection() -> void
OpenTelemetry.Trace.BatchExportActivityProcessorOptions
OpenTelemetry.Trace.BatchExportActivityProcessorOptions.BatchExportActivityProcessorOptions() -> void
override OpenTelemetry.BaseExportProcessor<T>.OnForceFlush(int timeoutMilliseconds) -> bool

View File

@ -60,11 +60,10 @@ OpenTelemetry.Metrics.MetricPoint.BucketCounts.get -> long[]
OpenTelemetry.Metrics.MetricPoint.DoubleValue.get -> double
OpenTelemetry.Metrics.MetricPoint.EndTime.get -> System.DateTimeOffset
OpenTelemetry.Metrics.MetricPoint.ExplicitBounds.get -> double[]
OpenTelemetry.Metrics.MetricPoint.Keys.get -> string[]
OpenTelemetry.Metrics.MetricPoint.LongValue.get -> long
OpenTelemetry.Metrics.MetricPoint.MetricPoint() -> void
OpenTelemetry.Metrics.MetricPoint.StartTime.get -> System.DateTimeOffset
OpenTelemetry.Metrics.MetricPoint.Values.get -> object[]
OpenTelemetry.Metrics.MetricPoint.Tags.get -> OpenTelemetry.ReadOnlyTagCollection
OpenTelemetry.Metrics.MetricReader
OpenTelemetry.Metrics.MetricReader.Collect(int timeoutMilliseconds = -1) -> bool
OpenTelemetry.Metrics.MetricReader.Dispose() -> void
@ -92,6 +91,14 @@ OpenTelemetry.Metrics.MetricType.LongSum = 26 -> OpenTelemetry.Metrics.MetricTyp
OpenTelemetry.Metrics.MetricTypeExtensions
OpenTelemetry.Metrics.PeriodicExportingMetricReader
OpenTelemetry.Metrics.PeriodicExportingMetricReader.PeriodicExportingMetricReader(OpenTelemetry.BaseExporter<OpenTelemetry.Metrics.Metric> exporter, int exportIntervalMilliseconds = 60000, int exportTimeoutMilliseconds = 30000) -> void
OpenTelemetry.ReadOnlyTagCollection
OpenTelemetry.ReadOnlyTagCollection.Count.get -> int
OpenTelemetry.ReadOnlyTagCollection.Enumerator
OpenTelemetry.ReadOnlyTagCollection.Enumerator.Current.get -> System.Collections.Generic.KeyValuePair<string, object>
OpenTelemetry.ReadOnlyTagCollection.Enumerator.Enumerator() -> void
OpenTelemetry.ReadOnlyTagCollection.Enumerator.MoveNext() -> bool
OpenTelemetry.ReadOnlyTagCollection.GetEnumerator() -> OpenTelemetry.ReadOnlyTagCollection.Enumerator
OpenTelemetry.ReadOnlyTagCollection.ReadOnlyTagCollection() -> void
OpenTelemetry.Trace.BatchExportActivityProcessorOptions
OpenTelemetry.Trace.BatchExportActivityProcessorOptions.BatchExportActivityProcessorOptions() -> void
override OpenTelemetry.BaseExportProcessor<T>.OnForceFlush(int timeoutMilliseconds) -> bool

View File

@ -2,6 +2,10 @@
## Unreleased
* Added `ReadOnlyTagCollection` and expose `Tags` on `MetricPoint` instead of
`Keys`+`Values`
([#2642](https://github.com/open-telemetry/opentelemetry-dotnet/pull/2642))
## 1.2.0-beta2
Released 2021-Nov-19

View File

@ -15,18 +15,20 @@
// </copyright>
using System;
using System.Diagnostics;
using System.Threading;
namespace OpenTelemetry.Metrics
{
public struct MetricPoint
{
private readonly AggregationType aggType;
private readonly object lockObject;
private readonly long[] bucketCounts;
private long longVal;
private long lastLongSum;
private double doubleVal;
private double lastDoubleSum;
private object lockObject;
private long[] bucketCounts;
internal MetricPoint(
AggregationType aggType,
@ -35,10 +37,11 @@ namespace OpenTelemetry.Metrics
object[] values,
double[] histogramBounds)
{
this.AggType = aggType;
Debug.Assert((keys?.Length ?? 0) == (values?.Length ?? 0), "Key and value array lengths did not match.");
this.aggType = aggType;
this.StartTime = startTime;
this.Keys = keys;
this.Values = values;
this.Tags = new ReadOnlyTagCollection(keys, values);
this.EndTime = default;
this.LongValue = default;
this.longVal = default;
@ -48,14 +51,14 @@ namespace OpenTelemetry.Metrics
this.lastDoubleSum = default;
this.MetricPointStatus = MetricPointStatus.NoCollectPending;
if (this.AggType == AggregationType.Histogram)
if (this.aggType == AggregationType.Histogram)
{
this.ExplicitBounds = histogramBounds;
this.BucketCounts = new long[this.ExplicitBounds.Length + 1];
this.bucketCounts = new long[this.ExplicitBounds.Length + 1];
this.lockObject = new object();
}
else if (this.AggType == AggregationType.HistogramSumCount)
else if (this.aggType == AggregationType.HistogramSumCount)
{
this.ExplicitBounds = null;
this.BucketCounts = null;
@ -71,9 +74,10 @@ namespace OpenTelemetry.Metrics
}
}
public string[] Keys { get; internal set; }
public object[] Values { get; internal set; }
/// <summary>
/// Gets the tags associated with the metric point.
/// </summary>
public ReadOnlyTagCollection Tags { get; }
public DateTimeOffset StartTime { get; internal set; }
@ -89,11 +93,9 @@ namespace OpenTelemetry.Metrics
internal MetricPointStatus MetricPointStatus { get; private set; }
private readonly AggregationType AggType { get; }
internal void Update(long number)
{
switch (this.AggType)
switch (this.aggType)
{
case AggregationType.LongSumIncomingDelta:
{
@ -137,7 +139,7 @@ namespace OpenTelemetry.Metrics
internal void Update(double number)
{
switch (this.AggType)
switch (this.aggType)
{
case AggregationType.DoubleSumIncomingDelta:
{
@ -213,7 +215,7 @@ namespace OpenTelemetry.Metrics
internal void TakeSnapshot(bool outputDelta)
{
switch (this.AggType)
switch (this.aggType)
{
case AggregationType.LongSumIncomingDelta:
case AggregationType.LongSumIncomingCumulative:

View File

@ -0,0 +1,95 @@
// <copyright file="ReadOnlyTagCollection.cs" company="OpenTelemetry Authors">
// 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.
// </copyright>
using System.Collections.Generic;
namespace OpenTelemetry
{
/// <summary>
/// A read-only collection of tag key/value pairs.
/// </summary>
// Note: Does not implement IReadOnlyCollection<> or IEnumerable<> to
// prevent accidental boxing.
public readonly struct ReadOnlyTagCollection
{
private readonly string[] keys;
private readonly object[] values;
internal ReadOnlyTagCollection(string[] keys, object[] values)
{
this.keys = keys;
this.values = values;
}
/// <summary>
/// Gets the number of tags in the collection.
/// </summary>
public int Count => this.keys?.Length ?? 0;
/// <summary>
/// Returns an enumerator that iterates through the tags.
/// </summary>
/// <returns><see cref="Enumerator"/>.</returns>
public Enumerator GetEnumerator() => new(this);
/// <summary>
/// Enumerates the elements of a <see cref="ReadOnlyTagCollection"/>.
/// </summary>
// Note: Does not implement IEnumerator<> to prevent accidental boxing.
public struct Enumerator
{
private readonly ReadOnlyTagCollection source;
private int index;
internal Enumerator(ReadOnlyTagCollection source)
{
this.source = source;
this.index = 0;
this.Current = default;
}
/// <summary>
/// Gets the tag at the current position of the enumerator.
/// </summary>
public KeyValuePair<string, object> Current { get; private set; }
/// <summary>
/// Advances the enumerator to the next element of the <see
/// cref="ReadOnlyTagCollection"/>.
/// </summary>
/// <returns><see langword="true"/> if the enumerator was
/// successfully advanced to the next element; <see
/// langword="false"/> if the enumerator has passed the end of the
/// collection.</returns>
public bool MoveNext()
{
int index = this.index;
if (index < this.source.Count)
{
this.Current = new KeyValuePair<string, object>(
this.source.keys[index],
this.source.values[index]);
this.index++;
return true;
}
return false;
}
}
}
}

View File

@ -113,10 +113,11 @@ namespace OpenTelemetry.Instrumentation.AspNetCore.Tests
Assert.Equal(1, bucket.Count);
*/
var attributes = new KeyValuePair<string, object>[metricPoint.Keys.Length];
for (int i = 0; i < attributes.Length; i++)
var attributes = new KeyValuePair<string, object>[metricPoint.Tags.Count];
int i = 0;
foreach (var tag in metricPoint.Tags)
{
attributes[i] = new KeyValuePair<string, object>(metricPoint.Keys[i], metricPoint.Values[i]);
attributes[i++] = tag;
}
var method = new KeyValuePair<string, object>(SemanticConventions.AttributeHttpMethod, "GET");

View File

@ -162,10 +162,11 @@ namespace OpenTelemetry.Instrumentation.Http.Tests
Assert.Equal(1L, metricPoint.LongValue);
Assert.Equal(activity.Duration.TotalMilliseconds, metricPoint.DoubleValue);
var attributes = new KeyValuePair<string, object>[metricPoint.Keys.Length];
for (int i = 0; i < attributes.Length; i++)
var attributes = new KeyValuePair<string, object>[metricPoint.Tags.Count];
int i = 0;
foreach (var tag in metricPoint.Tags)
{
attributes[i] = new KeyValuePair<string, object>(metricPoint.Keys[i], metricPoint.Values[i]);
attributes[i++] = tag;
}
var method = new KeyValuePair<string, object>(SemanticConventions.AttributeHttpMethod, tc.Method);

View File

@ -66,8 +66,7 @@ namespace OpenTelemetry.Metrics.Tests
Assert.Single(metricPoints);
var metricPoint = metricPoints[0];
Assert.Equal(100, metricPoint.LongValue);
Assert.NotNull(metricPoint.Keys);
Assert.NotNull(metricPoint.Values);
Assert.True(metricPoint.Tags.Count > 0);
}
[Fact]
@ -97,8 +96,7 @@ namespace OpenTelemetry.Metrics.Tests
Assert.Single(metricPoints);
var metricPoint = metricPoints[0];
Assert.Equal(100, metricPoint.LongValue);
Assert.NotNull(metricPoint.Keys);
Assert.NotNull(metricPoint.Values);
Assert.True(metricPoint.Tags.Count > 0);
}
[Theory]