-
Notifications
You must be signed in to change notification settings - Fork 862
Update Prometheus exporter name and unit processing #4753
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
CodeBlanch
merged 12 commits into
open-telemetry:main
from
JamesNK:jamesnk/prometheus-exporter-unit
Aug 16, 2023
Merged
Changes from 6 commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
ac79c1c
Update Prometheus exporter name and unit processing
JamesNK 1b041cc
Clean up
JamesNK 0077081
Fix build
JamesNK d6fc93f
PR feedback and comments
JamesNK eab4bea
seal
JamesNK b252965
PR feedback
JamesNK 84d0f6e
Update src/OpenTelemetry.Exporter.Prometheus.HttpListener/Internal/Pr…
JamesNK ad25e7f
Refactor cache to belong to manager
JamesNK 6357abf
Comment
JamesNK e8f6568
Merge branch 'main' into jamesnk/prometheus-exporter-unit
utpilla 4797cea
Update readme files
JamesNK d51688e
Merge branch 'main' into jamesnk/prometheus-exporter-unit
CodeBlanch File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
266 changes: 266 additions & 0 deletions
266
src/OpenTelemetry.Exporter.Prometheus.HttpListener/Internal/PrometheusMetric.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,266 @@ | ||
| // <copyright file="PrometheusMetric.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.Text; | ||
|
|
||
| namespace OpenTelemetry.Exporter.Prometheus; | ||
|
|
||
| internal sealed class PrometheusMetric | ||
| { | ||
| public PrometheusMetric(string name, string unit, PrometheusType type) | ||
| { | ||
| // The metric name is | ||
| // required to match the regex: `[a-zA-Z_:]([a-zA-Z0-9_:])*`. Invalid characters | ||
| // in the metric name MUST be replaced with the `_` character. Multiple | ||
| // consecutive `_` characters MUST be replaced with a single `_` character. | ||
| // https://github.com/open-telemetry/opentelemetry-specification/blob/b2f923fb1650dde1f061507908b834035506a796/specification/compatibility/prometheus_and_openmetrics.md#L230-L233 | ||
| var sanitizedName = SanitizeMetricName(name); | ||
|
|
||
| string sanitizedUnit = null; | ||
| if (!string.IsNullOrEmpty(unit)) | ||
| { | ||
| sanitizedUnit = GetUnit(unit); | ||
|
|
||
| // The resulting unit SHOULD be added to the metric as | ||
| // [OpenMetrics UNIT metadata](https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md#metricfamily) | ||
| // and as a suffix to the metric name unless the metric name already contains the | ||
| // unit, or the unit MUST be omitted. The unit suffix comes before any | ||
| // type-specific suffixes. | ||
| // https://github.com/open-telemetry/opentelemetry-specification/blob/b2f923fb1650dde1f061507908b834035506a796/specification/compatibility/prometheus_and_openmetrics.md#L242-L246 | ||
| if (!sanitizedName.Contains(sanitizedUnit)) | ||
| { | ||
| sanitizedName = sanitizedName + "_" + sanitizedUnit; | ||
| } | ||
| } | ||
|
|
||
| // If the metric name for monotonic Sum metric points does not end in a suffix of `_total` a suffix of `_total` MUST be added by default, otherwise the name MUST remain unchanged. | ||
| // Exporters SHOULD provide a configuration option to disable the addition of `_total` suffixes. | ||
| // https://github.com/open-telemetry/opentelemetry-specification/blob/b2f923fb1650dde1f061507908b834035506a796/specification/compatibility/prometheus_and_openmetrics.md#L286 | ||
| if (type == PrometheusType.Counter && !sanitizedName.Contains("total")) | ||
JamesNK marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| { | ||
| sanitizedName += "_total"; | ||
| } | ||
|
|
||
| // Special case: Converting "1" to "ratio". | ||
| // https://github.com/open-telemetry/opentelemetry-specification/blob/b2f923fb1650dde1f061507908b834035506a796/specification/compatibility/prometheus_and_openmetrics.md#L239 | ||
| if (type == PrometheusType.Gauge && unit == "1" && !sanitizedName.Contains("ratio")) | ||
| { | ||
| sanitizedName += "_ratio"; | ||
| } | ||
|
|
||
| this.Name = sanitizedName; | ||
| this.Unit = sanitizedUnit; | ||
| this.Type = type; | ||
| } | ||
|
|
||
| public string Name { get; } | ||
|
|
||
| public string Unit { get; } | ||
|
|
||
| public PrometheusType Type { get; } | ||
|
|
||
| internal static string SanitizeMetricName(string metricName) | ||
| { | ||
| StringBuilder sb = null; | ||
| var lastCharUnderscore = false; | ||
|
|
||
| for (var i = 0; i < metricName.Length; i++) | ||
| { | ||
| var c = metricName[i]; | ||
|
|
||
| if (i == 0 && char.IsNumber(c)) | ||
| { | ||
| sb ??= CreateStringBuilder(metricName); | ||
| sb.Append('_'); | ||
| lastCharUnderscore = true; | ||
| continue; | ||
| } | ||
|
|
||
| if (!char.IsLetterOrDigit(c) && c != ':') | ||
| { | ||
| if (!lastCharUnderscore) | ||
| { | ||
| lastCharUnderscore = true; | ||
| sb ??= CreateStringBuilder(metricName); | ||
| sb.Append('_'); | ||
| } | ||
| } | ||
| else | ||
| { | ||
| sb ??= CreateStringBuilder(metricName); | ||
| sb.Append(c); | ||
| lastCharUnderscore = false; | ||
| } | ||
| } | ||
|
|
||
| return sb?.ToString() ?? metricName; | ||
|
|
||
| static StringBuilder CreateStringBuilder(string name) => new StringBuilder(name.Length); | ||
JamesNK marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| internal static string RemoveAnnotations(string unit) | ||
| { | ||
| StringBuilder sb = null; | ||
|
|
||
| var hasOpenBrace = false; | ||
| var startOpenBraceIndex = 0; | ||
| var lastWriteIndex = 0; | ||
|
|
||
| for (var i = 0; i < unit.Length; i++) | ||
| { | ||
| var c = unit[i]; | ||
| if (c == '{') | ||
| { | ||
| if (!hasOpenBrace) | ||
| { | ||
| hasOpenBrace = true; | ||
| startOpenBraceIndex = i; | ||
| } | ||
| } | ||
| else if (c == '}') | ||
| { | ||
| if (hasOpenBrace) | ||
| { | ||
| sb ??= new StringBuilder(); | ||
| sb.Append(unit, lastWriteIndex, startOpenBraceIndex - lastWriteIndex); | ||
| hasOpenBrace = false; | ||
| lastWriteIndex = i + 1; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| if (lastWriteIndex == 0) | ||
| { | ||
| return unit; | ||
| } | ||
|
|
||
| sb.Append(unit, lastWriteIndex, unit.Length - lastWriteIndex); | ||
| return sb.ToString(); | ||
| } | ||
|
|
||
| private static string GetUnit(string unit) | ||
| { | ||
| // Dropping the portions of the Unit within brackets (e.g. {packet}). Brackets MUST NOT be included in the resulting unit. A "count of foo" is considered unitless in Prometheus. | ||
| // https://github.com/open-telemetry/opentelemetry-specification/blob/b2f923fb1650dde1f061507908b834035506a796/specification/compatibility/prometheus_and_openmetrics.md#L238 | ||
| var updatedUnit = RemoveAnnotations(unit); | ||
|
|
||
| // Converting "foo/bar" to "foo_per_bar". | ||
| // https://github.com/open-telemetry/opentelemetry-specification/blob/b2f923fb1650dde1f061507908b834035506a796/specification/compatibility/prometheus_and_openmetrics.md#L240C3-L240C41 | ||
| if (TryProcessRateUnits(updatedUnit, out var updatedPerUnit)) | ||
| { | ||
| updatedUnit = updatedPerUnit; | ||
| } | ||
| else | ||
| { | ||
| // Converting from abbreviations to full words (e.g. "ms" to "milliseconds"). | ||
| // https://github.com/open-telemetry/opentelemetry-specification/blob/b2f923fb1650dde1f061507908b834035506a796/specification/compatibility/prometheus_and_openmetrics.md#L237 | ||
| updatedUnit = MapUnit(updatedUnit.AsSpan()); | ||
| } | ||
|
|
||
| return updatedUnit; | ||
| } | ||
|
|
||
| private static bool TryProcessRateUnits(string updatedUnit, out string updatedPerUnit) | ||
| { | ||
| updatedPerUnit = null; | ||
|
|
||
| for (int i = 0; i < updatedUnit.Length; i++) | ||
| { | ||
| if (updatedUnit[i] == '/') | ||
| { | ||
| // Only convert rate expressed units if it's a valid expression. | ||
| if (i == updatedUnit.Length - 1) | ||
| { | ||
| return false; | ||
| } | ||
|
|
||
| updatedPerUnit = MapUnit(updatedUnit.AsSpan(0, i)) + "_per_" + MapPerUnit(updatedUnit.AsSpan(i + 1, updatedUnit.Length - i - 1)); | ||
| return true; | ||
| } | ||
| } | ||
|
|
||
| return false; | ||
| } | ||
|
|
||
| // The map to translate OTLP units to Prometheus units | ||
| // OTLP metrics use the c/s notation as specified at https://ucum.org/ucum.html | ||
| // (See also https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/semantic_conventions/README.md#instrument-units) | ||
| // Prometheus best practices for units: https://prometheus.io/docs/practices/naming/#base-units | ||
| // OpenMetrics specification for units: https://github.com/OpenObservability/OpenMetrics/blob/main/specification/OpenMetrics.md#units-and-base-units | ||
| private static string MapUnit(ReadOnlySpan<char> unit) | ||
| { | ||
| return unit switch | ||
| { | ||
| // Time | ||
| "d" => "days", | ||
| "h" => "hours", | ||
| "min" => "minutes", | ||
| "s" => "seconds", | ||
| "ms" => "milliseconds", | ||
| "us" => "microseconds", | ||
| "ns" => "nanoseconds", | ||
|
|
||
| // Bytes | ||
| "By" => "bytes", | ||
| "KiBy" => "kibibytes", | ||
| "MiBy" => "mebibytes", | ||
| "GiBy" => "gibibytes", | ||
| "TiBy" => "tibibytes", | ||
| "KBy" => "kilobytes", | ||
| "MBy" => "megabytes", | ||
| "GBy" => "gigabytes", | ||
| "TBy" => "terabytes", | ||
| "B" => "bytes", | ||
| "KB" => "kilobytes", | ||
| "MB" => "megabytes", | ||
| "GB" => "gigabytes", | ||
| "TB" => "terabytes", | ||
|
|
||
| // SI | ||
| "m" => "meters", | ||
| "V" => "volts", | ||
| "A" => "amperes", | ||
| "J" => "joules", | ||
| "W" => "watts", | ||
| "g" => "grams", | ||
|
|
||
| // Misc | ||
| "Cel" => "celsius", | ||
| "Hz" => "hertz", | ||
| "1" => string.Empty, | ||
| "%" => "percent", | ||
| "$" => "dollars", | ||
| _ => unit.ToString(), | ||
JamesNK marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| }; | ||
| } | ||
|
|
||
| // The map that translates the "per" unit | ||
| // Example: s => per second (singular) | ||
| private static string MapPerUnit(ReadOnlySpan<char> perUnit) | ||
| { | ||
| return perUnit switch | ||
| { | ||
| "s" => "second", | ||
| "m" => "minute", | ||
| "h" => "hour", | ||
| "d" => "day", | ||
| "w" => "week", | ||
| "mo" => "month", | ||
| "y" => "year", | ||
| _ => perUnit.ToString(), | ||
| }; | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.