pax_global_header00006660000000000000000000000064152014673470014523gustar00rootroot0000000000000052 comment=fc4ab5d99ca7f6f1f85328a101250392966d30e8 golang-github-prometheus-otlptranslator-1.0.0/000077500000000000000000000000001520146734700215275ustar00rootroot00000000000000golang-github-prometheus-otlptranslator-1.0.0/.github/000077500000000000000000000000001520146734700230675ustar00rootroot00000000000000golang-github-prometheus-otlptranslator-1.0.0/.github/CODEOWNERS000066400000000000000000000000521520146734700244570ustar00rootroot00000000000000* @aknuds1 @jesusvazquez @ArthurSens @ywwggolang-github-prometheus-otlptranslator-1.0.0/.github/PULL_REQUEST_TEMPLATE.md000066400000000000000000000015431520146734700266730ustar00rootroot00000000000000 golang-github-prometheus-otlptranslator-1.0.0/.github/dependabot.yml000066400000000000000000000001561520146734700257210ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "gomod" directory: "/" schedule: interval: "monthly" golang-github-prometheus-otlptranslator-1.0.0/.github/workflows/000077500000000000000000000000001520146734700251245ustar00rootroot00000000000000golang-github-prometheus-otlptranslator-1.0.0/.github/workflows/ci.yml000066400000000000000000000005541520146734700262460ustar00rootroot00000000000000--- name: CI on: pull_request: push: permissions: # added using https://github.com/step-security/secure-repo contents: read jobs: test_go: name: Go tests runs-on: ubuntu-latest container: image: golang:1.24.1-alpine steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - run: go test ./... golang-github-prometheus-otlptranslator-1.0.0/.github/workflows/golangci-lint.yml000066400000000000000000000024271520146734700304030ustar00rootroot00000000000000--- # This action is synced from https://github.com/prometheus/prometheus name: golangci-lint on: push: paths: - "go.sum" - "go.mod" - "**.go" - "scripts/errcheck_excludes.txt" - ".github/workflows/golangci-lint.yml" - ".golangci.yml" pull_request: permissions: # added using https://github.com/step-security/secure-repo contents: read jobs: golangci: permissions: contents: read # for actions/checkout to fetch code pull-requests: read # for golangci/golangci-lint-action to fetch pull requests name: lint runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: persist-credentials: false - name: Install Go uses: actions/setup-go@d35c59abb061a4a6fb18e82ac0862c26744d6ab5 # v5.5.0 with: go-version: 1.25.x - name: Install snmp_exporter/generator dependencies run: sudo apt-get update && sudo apt-get -y install libsnmp-dev if: github.repository == 'prometheus/snmp_exporter' - name: Lint uses: golangci/golangci-lint-action@4afd733a84b1f43292c63897423277bb7f4313a9 # v8.0.0 with: args: --verbose version: v2.2.1 golang-github-prometheus-otlptranslator-1.0.0/.gitignore000066400000000000000000000007731520146734700235260ustar00rootroot00000000000000# If you prefer the allow list template instead of the deny list, see community template: # https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore # # Binaries for programs and plugins *.exe *.exe~ *.dll *.so *.dylib # Test binary, built with `go test -c` *.test # Output of the go coverage tool, specifically when used with LiteIDE *.out # Dependency directories (remove the comment below to include it) # vendor/ # Go workspace file go.work go.work.sum # env file .env golang-github-prometheus-otlptranslator-1.0.0/.golangci.yml000066400000000000000000000057031520146734700241200ustar00rootroot00000000000000formatters: enable: - gci - gofumpt settings: gci: sections: - standard - default - prefix(github.com/prometheus/otlptranslator) gofumpt: extra-rules: true issues: max-issues-per-linter: 0 max-same-issues: 0 linters: # Keep this list sorted alphabetically enable: - depguard - errorlint - exptostd - gocritic - godot - loggercheck - misspell - nilnesserr # TODO: Enable once https://github.com/golangci/golangci-lint/issues/3228 is fixed. # - nolintlint - perfsprint - predeclared - revive - sloglint - testifylint - unconvert - unused - usestdlibvars - whitespace settings: depguard: rules: main: deny: - pkg: sync/atomic desc: Use go.uber.org/atomic instead of sync/atomic - pkg: github.com/stretchr/testify/assert desc: Use github.com/stretchr/testify/require instead of github.com/stretchr/testify/assert - pkg: io/ioutil desc: Use corresponding 'os' or 'io' functions instead. - pkg: github.com/pkg/errors desc: Use 'errors' or 'fmt' instead of github.com/pkg/errors - pkg: golang.org/x/exp/slices desc: Use 'slices' instead. perfsprint: # Optimizes `fmt.Errorf`. errorf: true revive: # By default, revive will enable only the linting rules that are named in the configuration file. # So, it's needed to explicitly enable all required rules here. rules: # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md - name: blank-imports - name: comment-spacings - name: context-as-argument arguments: # Allow functions with test or bench signatures. - allowTypesBefore: '*testing.T,testing.TB' - name: context-keys-type - name: dot-imports - name: early-return arguments: - preserveScope # A lot of false positives: incorrectly identifies channel draining as "empty code block". # See https://github.com/mgechev/revive/issues/386 - name: empty-block disabled: true - name: error-naming - name: error-return - name: error-strings - name: errorf - name: exported - name: increment-decrement - name: indent-error-flow arguments: - preserveScope - name: range - name: receiver-naming - name: redefines-builtin-id - name: superfluous-else arguments: - preserveScope - name: time-naming - name: unexported-return - name: unreachable-code - name: unused-parameter - name: var-declaration - name: var-naming testifylint: disable: - float-compare - go-require enable-all: true run: timeout: 15m version: "2" golang-github-prometheus-otlptranslator-1.0.0/CODE_OF_CONDUCT.md000066400000000000000000000002301520146734700243210ustar00rootroot00000000000000# Prometheus Community Code of Conduct Prometheus follows the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/main/code-of-conduct.md). golang-github-prometheus-otlptranslator-1.0.0/LICENSE000066400000000000000000000261351520146734700225430ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] 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. golang-github-prometheus-otlptranslator-1.0.0/MAINTAINERS.md000066400000000000000000000003411520146734700236210ustar00rootroot00000000000000* Arthur Silva Sens (arthursens2005@gmail.com / @ArthurSens) * Arve Knudsen (arve.knudsen@gmail.com / @aknuds1) * Jesús Vázquez (jesus.vazquez@grafana.com / @jesusvazquez) * Owen Williams (owen.williams@grafana.com / @ywwg)golang-github-prometheus-otlptranslator-1.0.0/README.md000066400000000000000000000102001520146734700227770ustar00rootroot00000000000000# OTLP Prometheus Translator A Go library for converting [OpenTelemetry Protocol (OTLP)](https://opentelemetry.io/docs/specs/otlp/) metric and attribute names to [Prometheus](https://prometheus.io/)-compliant formats. This is an internal library for both Prometheus and Open Telemetry, without any stability guarantees for external usage. Part of the [Prometheus](https://prometheus.io/) ecosystem, following the [OpenTelemetry to Prometheus compatibility specification](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/compatibility/prometheus_and_openmetrics.md). ## Features - **Metric Name and Label Translation**: Convert OTLP metric names and attributes to Prometheus-compliant format - **Unit Handling**: Translate OTLP units to Prometheus unit conventions - **Type-Aware Suffixes**: Optionally append `_total`, `_ratio` based on metric type - **Namespace Support**: Add configurable namespace prefixes - **UTF-8 Support**: Choose between Prometheus legacy scheme compliant metric/label names (`[a-zA-Z0-9:_]`) or untranslated metric/label names - **Translation Strategy Configuration**: Select a translation strategy with a standard set of strings. ## Installation ```bash go get github.com/prometheus/otlptranslator ``` ## Quick Start ```go package main import ( "fmt" "github.com/prometheus/otlptranslator" ) func main() { // Create a metric namer using traditional Prometheus name translation, with suffixes added and UTF-8 disallowed. strategy := otlptranslator.UnderscoreEscapingWithSuffixes namer := otlptranslator.NewMetricNamer("myapp", strategy) // Translate OTLP metric to Prometheus format metric := otlptranslator.Metric{ Name: "http.server.request.duration", Unit: "s", Type: otlptranslator.MetricTypeHistogram, } fmt.Println(namer.Build(metric)) // Output: myapp_http_server_request_duration_seconds // Translate label names labelNamer := otlptranslator.LabelNamer{UTF8Allowed: false} fmt.Println(labelNamer.Build("http.method")) // Output: http_method } ``` ## Usage Examples ### Metric Name Translation ```go namer := otlptranslator.MetricNamer{WithMetricSuffixes: true, UTF8Allowed: false} // Counter gets _total suffix counter := otlptranslator.Metric{ Name: "requests.count", Unit: "1", Type: otlptranslator.MetricTypeMonotonicCounter, } fmt.Println(namer.Build(counter)) // requests_count_total // Gauge with unit conversion gauge := otlptranslator.Metric{ Name: "memory.usage", Unit: "By", Type: otlptranslator.MetricTypeGauge, } fmt.Println(namer.Build(gauge)) // memory_usage_bytes // Dimensionless gauge gets _ratio suffix ratio := otlptranslator.Metric{ Name: "cpu.utilization", Unit: "1", Type: otlptranslator.MetricTypeGauge, } fmt.Println(namer.Build(ratio)) // cpu_utilization_ratio ``` ### Label Translation ```go labelNamer := otlptranslator.LabelNamer{UTF8Allowed: false} labelNamer.Build("http.method") // http_method labelNamer.Build("123invalid") // key_123invalid labelNamer.Build("_private") // key_private labelNamer.Build("__reserved__") // __reserved__ (preserved) labelNamer.Build("label@with$symbols") // label_with_symbols ``` ### Unit Translation ```go unitNamer := otlptranslator.UnitNamer{UTF8Allowed: false} unitNamer.Build("s") // seconds unitNamer.Build("By") // bytes unitNamer.Build("requests/s") // requests_per_second unitNamer.Build("1") // "" (dimensionless) ``` ### Configuration Options ```go // Prometheus-compliant mode - supports [a-zA-Z0-9:_] compliantNamer := otlptranslator.MetricNamer{UTF8Allowed: false, WithMetricSuffixes: true} // Transparent pass-through mode, aka "NoTranslation" utf8Namer := otlptranslator.MetricNamer{UTF8Allowed: true, WithMetricSuffixes: false} utf8Namer = otlptranslator.NewMetricNamer("", otlpTranslator.NoTranslation) // With namespace and suffixes productionNamer := otlptranslator.MetricNamer{ Namespace: "myservice", WithMetricSuffixes: true, UTF8Allowed: false, } ``` ## License Licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details. golang-github-prometheus-otlptranslator-1.0.0/SECURITY.md000066400000000000000000000002541520146734700233210ustar00rootroot00000000000000# Reporting a security issue The Prometheus security policy, including how to report vulnerabilities, can be found here: golang-github-prometheus-otlptranslator-1.0.0/constants.go000066400000000000000000000047651520146734700241060ustar00rootroot00000000000000// Copyright 2025 The Prometheus 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 otlptranslator const ( // ExemplarTraceIDKey is the key used to store the trace ID in Prometheus // exemplars: // https://github.com/open-telemetry/opentelemetry-specification/blob/e6eccba97ebaffbbfad6d4358408a2cead0ec2df/specification/compatibility/prometheus_and_openmetrics.md#exemplars ExemplarTraceIDKey = "trace_id" // ExemplarSpanIDKey is the key used to store the Span ID in Prometheus // exemplars: // https://github.com/open-telemetry/opentelemetry-specification/blob/e6eccba97ebaffbbfad6d4358408a2cead0ec2df/specification/compatibility/prometheus_and_openmetrics.md#exemplars ExemplarSpanIDKey = "span_id" // ScopeNameLabelKey is the name of the label key used to identify the name // of the OpenTelemetry scope which produced the metric: // https://github.com/open-telemetry/opentelemetry-specification/blob/e6eccba97ebaffbbfad6d4358408a2cead0ec2df/specification/compatibility/prometheus_and_openmetrics.md#instrumentation-scope ScopeNameLabelKey = "otel_scope_name" // ScopeVersionLabelKey is the name of the label key used to identify the // version of the OpenTelemetry scope which produced the metric: // https://github.com/open-telemetry/opentelemetry-specification/blob/e6eccba97ebaffbbfad6d4358408a2cead0ec2df/specification/compatibility/prometheus_and_openmetrics.md#instrumentation-scope ScopeVersionLabelKey = "otel_scope_version" // TargetInfoMetricName is the name of the metric used to preserve resource // attributes in Prometheus format: // https://github.com/open-telemetry/opentelemetry-specification/blob/e6eccba97ebaffbbfad6d4358408a2cead0ec2df/specification/compatibility/prometheus_and_openmetrics.md#resource-attributes-1 // It originates from OpenMetrics: // https://github.com/OpenObservability/OpenMetrics/blob/1386544931307dff279688f332890c31b6c5de36/specification/OpenMetrics.md#supporting-target-metadata-in-both-push-based-and-pull-based-systems TargetInfoMetricName = "target_info" ) golang-github-prometheus-otlptranslator-1.0.0/doc.go000066400000000000000000000022641520146734700226270ustar00rootroot00000000000000// Copyright 2025 The Prometheus 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 otlptranslator provides utilities for converting OpenTelemetry Protocol (OTLP) // metric and attribute names to Prometheus-compliant formats. // // This package is designed to help users translate OpenTelemetry metrics to Prometheus // metrics while following the official OpenTelemetry to Prometheus compatibility specification. // // Main components: // - MetricNamer: Translates OTLP metric names to Prometheus metric names // - LabelNamer: Translates OTLP attribute names to Prometheus label names // - UnitNamer: Translates OTLP units to Prometheus unit conventions package otlptranslator golang-github-prometheus-otlptranslator-1.0.0/go.mod000066400000000000000000000001131520146734700226300ustar00rootroot00000000000000module github.com/prometheus/otlptranslator go 1.23.0 toolchain go1.24.1 golang-github-prometheus-otlptranslator-1.0.0/go.sum000066400000000000000000000000001520146734700226500ustar00rootroot00000000000000golang-github-prometheus-otlptranslator-1.0.0/label_namer.go000066400000000000000000000075671520146734700243360ustar00rootroot00000000000000// Copyright 2025 The Prometheus 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. // Provenance-includes-location: https://github.com/prometheus/prometheus/blob/93e991ef7ed19cc997a9360c8016cac3767b8057/storage/remote/otlptranslator/prometheus/normalize_label.go // Provenance-includes-license: Apache-2.0 // Provenance-includes-copyright: Copyright The Prometheus Authors // Provenance-includes-location: https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/95e8f8fdc2a9dc87230406c9a3cf02be4fd68bea/pkg/translator/prometheus/normalize_label.go // Provenance-includes-license: Apache-2.0 // Provenance-includes-copyright: Copyright The OpenTelemetry Authors. package otlptranslator import ( "errors" "fmt" "strings" "unicode" ) // LabelNamer is a helper struct to build label names. // It translates OpenTelemetry Protocol (OTLP) attribute names to Prometheus-compliant label names. // // Example usage: // // namer := LabelNamer{UTF8Allowed: false} // result := namer.Build("http.method") // "http_method" type LabelNamer struct { UTF8Allowed bool // UnderscoreLabelSanitization, if true, enabled prepending 'key' to labels // starting with '_'. Reserved labels starting with `__` are not modified. // // Deprecated: This will be removed in a future version of otlptranslator. UnderscoreLabelSanitization bool // PreserveMultipleUnderscores enables preserving of multiple // consecutive underscores in label names when UTF8Allowed is false. // This option is discouraged as it violates the OpenTelemetry to Prometheus // specification https://github.com/open-telemetry/opentelemetry-specification/blob/v1.38.0/specification/compatibility/prometheus_and_openmetrics.md#otlp-metric-points-to-prometheus), // but may be needed for compatibility with legacy systems that rely on the old behavior. PreserveMultipleUnderscores bool } // Build normalizes the specified label to follow Prometheus label names standard. // // Translation rules: // - Replaces invalid characters with underscores // - Prefixes labels with invalid start characters (numbers or `_`) with "key" // - Preserves double underscore labels (reserved names) // - If UTF8Allowed is true, returns label as-is // // Examples: // // namer := LabelNamer{UTF8Allowed: false} // namer.Build("http.method") // "http_method" // namer.Build("123invalid") // "key_123invalid" // namer.Build("__reserved__") // "__reserved__" (preserved) func (ln *LabelNamer) Build(label string) (string, error) { if len(label) == 0 { return "", errors.New("label name is empty") } if ln.UTF8Allowed { if hasUnderscoresOnly(label) { return "", fmt.Errorf("label name %q contains only underscores", label) } return label, nil } normalizedName := sanitizeLabelName(label, ln.PreserveMultipleUnderscores) // If label starts with a number, prepend with "key_". if unicode.IsDigit(rune(normalizedName[0])) { normalizedName = "key_" + normalizedName } else if ln.UnderscoreLabelSanitization && strings.HasPrefix(normalizedName, "_") && !strings.HasPrefix(normalizedName, "__") { normalizedName = "key" + normalizedName } if hasUnderscoresOnly(normalizedName) { return "", fmt.Errorf("normalization for label name %q resulted in invalid name %q", label, normalizedName) } return normalizedName, nil } func hasUnderscoresOnly(label string) bool { for _, c := range label { if c != '_' { return false } } return true } golang-github-prometheus-otlptranslator-1.0.0/label_namer_bench_test.go000066400000000000000000000021101520146734700265070ustar00rootroot00000000000000package otlptranslator import "testing" var labelBenchmarkInputs = []struct { name string label string }{ { name: "empty label", label: "", }, { name: "label with colons", label: "label:with:colons", }, { name: "label with capital letters", label: "LabelWithCapitalLetters", }, { name: "label with special characters", label: "label!with&special$chars)", }, { name: "label with foreign characters", label: "label_with_foreign_characters_字符", }, { name: "label with dots", label: "label.with.dots", }, { name: "label starting with digits", label: "123label", }, { name: "label starting with underscores", label: "_label_starting_with_underscore", }, { name: "label starting with 2 underscores", label: "__label_starting_with_2underscores", }, } func BenchmarkNormalizeLabel(b *testing.B) { labelNamer := LabelNamer{UTF8Allowed: false} for _, input := range labelBenchmarkInputs { b.Run(input.name, func(b *testing.B) { for i := 0; i < b.N; i++ { //nolint:errcheck labelNamer.Build(input.label) } }) } } golang-github-prometheus-otlptranslator-1.0.0/label_namer_test.go000066400000000000000000000143511520146734700253620ustar00rootroot00000000000000// Copyright 2025 The Prometheus 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. // Provenance-includes-location: https://github.com/prometheus/prometheus/blob/93e991ef7ed19cc997a9360c8016cac3767b8057/storage/remote/otlptranslator/prometheus/normalize_label_test.go // Provenance-includes-license: Apache-2.0 // Provenance-includes-copyright: Copyright The Prometheus Authors package otlptranslator import ( "testing" ) var labelTestCases = []struct { label string sanitized string sanitizedMultipleUnderscores string }{ {label: "label:with:colons", sanitized: "label_with_colons"}, {label: "LabelWithCapitalLetters", sanitized: "LabelWithCapitalLetters"}, {label: "label!with&special$chars)", sanitized: "label_with_special_chars_"}, { label: "label_with_foreign_characters_字符", sanitized: "label_with_foreign_characters_", sanitizedMultipleUnderscores: "label_with_foreign_characters___", }, {label: "label.with.dots", sanitized: "label_with_dots"}, {label: "123label", sanitized: "key_123label"}, {label: "_label_starting_with_underscore", sanitized: "_label_starting_with_underscore"}, { label: "__label_starting_with_2underscores", sanitized: "_label_starting_with_2underscores", sanitizedMultipleUnderscores: "__label_starting_with_2underscores", }, {label: "ようこそ", sanitized: ""}, { label: "label__with__double__underscores", sanitized: "label_with_double_underscores", sanitizedMultipleUnderscores: "label__with__double__underscores", }, { label: "label.name__with&&special##chars", sanitized: "label_name_with_special_chars", sanitizedMultipleUnderscores: "label_name__with__special__chars", }, { label: "__reserved__label__name__", sanitized: "__reserved_label_name__", sanitizedMultipleUnderscores: "__reserved__label__name__", }, { label: "trailing_underscores___", sanitized: "trailing_underscores_", sanitizedMultipleUnderscores: "trailing_underscores___", }, } func TestBuildLabel(t *testing.T) { for _, tt := range labelTestCases { t.Run(tt.label, func(t *testing.T) { t.Run("Not preserving multiple underscores", func(t *testing.T) { labelNamer := LabelNamer{} got, _ := labelNamer.Build(tt.label) if got != tt.sanitized { t.Errorf("LabelNamer.Build(%q) = %q, want %q", tt.label, got, tt.sanitized) } }) t.Run("Preserving multiple underscores", func(t *testing.T) { labelNamer := LabelNamer{PreserveMultipleUnderscores: true} got, _ := labelNamer.Build(tt.label) want := tt.sanitized if tt.sanitizedMultipleUnderscores != "" { want = tt.sanitizedMultipleUnderscores } if got != want { t.Errorf("LabelNamer.Build(%q) = %q, want %q", tt.label, got, want) } }) }) } } func TestBuildLabel_UTF8Allowed(t *testing.T) { for _, tt := range labelTestCases { t.Run(tt.label, func(t *testing.T) { labelNamer := LabelNamer{UTF8Allowed: true} got, _ := labelNamer.Build(tt.label) if got != tt.label { t.Errorf("LabelNamer.Build(%q) = %q, want %q", tt.label, got, tt.label) } }) } } // TestBuildLabel_Underscores confirms that `key_` is only prepended to label // names starting with an underscore if UnderscoreLabelSanitization is true. // Labels starting with a number always get `key_` prepended so they are valid // Prometheus labels. func TestBuildLabel_Underscores(t *testing.T) { labelTestCases := []struct { label string sanitized string sanitizedUnderscores string }{ { label: "regular label", sanitized: "regular_label", sanitizedUnderscores: "regular_label", }, { label: "123label", sanitized: "key_123label", sanitizedUnderscores: "key_123label", }, { label: "_label_starting_with_underscore", sanitized: "_label_starting_with_underscore", sanitizedUnderscores: "key_label_starting_with_underscore", }, } for _, tt := range labelTestCases { t.Run(tt.label, func(t *testing.T) { labelNamer := LabelNamer{} got, err := labelNamer.Build(tt.label) if err != nil { t.Errorf("LabelNamer.Build(%q) returned err: %v", tt.label, got) } if got != tt.sanitized { t.Errorf("LabelNamer.Build(%q) = %q, want %q", tt.label, got, tt.sanitized) } labelNamer.UnderscoreLabelSanitization = true got, err = labelNamer.Build(tt.label) if err != nil { t.Errorf("LabelNamer.Build(%q) (underscore mode) returned err: %v", tt.label, got) } if got != tt.sanitizedUnderscores { t.Errorf("LabelNamer.Build(%q) (underscore mode) = %q, want %q", tt.label, got, tt.sanitizedUnderscores) } }) } } func TestBuildLabel_Errors(t *testing.T) { labelTestCases := []struct { label string wantEscapeErr bool wantUTF8err bool }{ {label: "", wantEscapeErr: true, wantUTF8err: true}, {label: "__", wantEscapeErr: true, wantUTF8err: true}, {label: "ようこそ", wantEscapeErr: true}, // Would be __ if UTF-8 isn't allowed } for _, tt := range labelTestCases { t.Run(tt.label, func(t *testing.T) { if tt.wantEscapeErr { labelNamer := LabelNamer{} got, err := labelNamer.Build(tt.label) if err == nil { t.Errorf("LabelNamer.Build(%q) returned nil err, wanted one, return value %v", tt.label, got) } } if tt.wantUTF8err { labelNamer := LabelNamer{UTF8Allowed: true} got, err := labelNamer.Build(tt.label) if err == nil { t.Errorf("LabelNamer.Build(%q) returned nil err, wanted one, return value %v", tt.label, got) } } }) } } golang-github-prometheus-otlptranslator-1.0.0/metric_namer.go000066400000000000000000000272441520146734700245340ustar00rootroot00000000000000// Copyright 2025 The Prometheus 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. // Provenance-includes-location: https://github.com/prometheus/prometheus/blob/93e991ef7ed19cc997a9360c8016cac3767b8057/storage/remote/otlptranslator/prometheus/metric_name_builder.go // Provenance-includes-license: Apache-2.0 // Provenance-includes-copyright: Copyright The Prometheus Authors // Provenance-includes-location: https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/95e8f8fdc2a9dc87230406c9a3cf02be4fd68bea/pkg/translator/prometheus/normalize_name.go // Provenance-includes-license: Apache-2.0 // Provenance-includes-copyright: Copyright The OpenTelemetry Authors. package otlptranslator import ( "fmt" "slices" "strings" "unicode" ) // 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/prometheus/OpenMetrics/blob/v1.0.0/specification/OpenMetrics.md#units-and-base-units var unitMap = map[string]string{ // 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", // SI "m": "meters", "V": "volts", "A": "amperes", "J": "joules", "W": "watts", "g": "grams", // Misc "Cel": "celsius", "Hz": "hertz", "1": "", "%": "percent", } // The map that translates the "per" unit. // Example: s => per second (singular). var perUnitMap = map[string]string{ "s": "second", "m": "minute", "h": "hour", "d": "day", "w": "week", "mo": "month", "y": "year", } // MetricNamer is a helper struct to build metric names. // It converts OpenTelemetry Protocol (OTLP) metric names to Prometheus-compliant metric names. // // Example usage: // // namer := MetricNamer{ // WithMetricSuffixes: true, // UTF8Allowed: false, // } // // metric := Metric{ // Name: "http.server.duration", // Unit: "s", // Type: MetricTypeHistogram, // } // // result := namer.Build(metric) // "http_server_duration_seconds" type MetricNamer struct { Namespace string WithMetricSuffixes bool UTF8Allowed bool } // NewMetricNamer creates a MetricNamer with the specified namespace (can be // blank) and the requested Translation Strategy. func NewMetricNamer(namespace string, strategy TranslationStrategyOption) MetricNamer { return MetricNamer{ Namespace: namespace, WithMetricSuffixes: strategy.ShouldAddSuffixes(), UTF8Allowed: !strategy.ShouldEscape(), } } // Metric is a helper struct that holds information about a metric. // It represents an OpenTelemetry metric with its name, unit, and type. // // Example: // // metric := Metric{ // Name: "http.server.request.duration", // Unit: "s", // Type: MetricTypeHistogram, // } type Metric struct { Name string Unit string Type MetricType } // Build builds a metric name for the specified metric. // // The method applies different transformations based on the MetricNamer configuration: // - If UTF8Allowed is true, doesn't translate names - all characters must be valid UTF-8, however. // - If UTF8Allowed is false, translates metric names to comply with legacy Prometheus name scheme by escaping invalid characters to `_`. // - If WithMetricSuffixes is true, adds appropriate suffixes based on type and unit. // // See rules at https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels // // Examples: // // namer := MetricNamer{WithMetricSuffixes: true, UTF8Allowed: false} // // // Counter gets _total suffix // counter := Metric{Name: "requests.count", Unit: "1", Type: MetricTypeMonotonicCounter} // result := namer.Build(counter) // "requests_count_total" // // // Gauge with unit suffix // gauge := Metric{Name: "memory.usage", Unit: "By", Type: MetricTypeGauge} // result = namer.Build(gauge) // "memory_usage_bytes" func (mn *MetricNamer) Build(metric Metric) (string, error) { if mn.UTF8Allowed { return mn.buildMetricName(metric.Name, metric.Unit, metric.Type) } return mn.buildCompliantMetricName(metric.Name, metric.Unit, metric.Type) } func (mn *MetricNamer) buildCompliantMetricName(name, unit string, metricType MetricType) (normalizedName string, err error) { defer func() { if len(normalizedName) == 0 { err = fmt.Errorf("normalization for metric %q resulted in empty name", name) return } if normalizedName == name { return } // Check that the resulting normalized name contains at least one non-underscore character for _, c := range normalizedName { if c != '_' { return } } err = fmt.Errorf("normalization for metric %q resulted in invalid name %q", name, normalizedName) normalizedName = "" }() // Full normalization following standard Prometheus naming conventions if mn.WithMetricSuffixes { normalizedName = normalizeName(name, unit, metricType, mn.Namespace) return } // Simple case (no full normalization, no units, etc.). metricName := strings.Join(strings.FieldsFunc(name, func(r rune) bool { return !isValidCompliantMetricChar(r) && r != '_' }), "_") // Namespace? if mn.Namespace != "" { namespace := strings.Join(strings.FieldsFunc(mn.Namespace, func(r rune) bool { return !isValidCompliantMetricChar(r) && r != '_' }), "_") normalizedName = namespace + "_" + metricName return } // Metric name starts with a digit? Prefix it with an underscore. if metricName != "" && unicode.IsDigit(rune(metricName[0])) { metricName = "_" + metricName } normalizedName = metricName return } // isValidCompliantMetricChar checks if a rune is a valid metric name character (a-z, A-Z, 0-9, :). func isValidCompliantMetricChar(r rune) bool { return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == ':' } // replaceInvalidMetricChar replaces invalid metric name characters with underscore. func replaceInvalidMetricChar(r rune) rune { if isValidCompliantMetricChar(r) { return r } return '_' } // Build a normalized name for the specified metric. func normalizeName(name, unit string, metricType MetricType, namespace string) string { // Split metric name into "tokens" (of supported metric name runes). // Note that this has the side effect of replacing multiple consecutive underscores with a single underscore. // This is part of the OTel to Prometheus specification: https://github.com/open-telemetry/opentelemetry-specification/blob/v1.38.0/specification/compatibility/prometheus_and_openmetrics.md#otlp-metric-points-to-prometheus. nameTokens := strings.FieldsFunc( name, func(r rune) bool { return !isValidCompliantMetricChar(r) }, ) mainUnitSuffix, perUnitSuffix := buildUnitSuffixes(unit) nameTokens = addUnitTokens(nameTokens, cleanUpUnit(mainUnitSuffix), cleanUpUnit(perUnitSuffix)) // Append _total for Counters if metricType == MetricTypeMonotonicCounter { nameTokens = append(removeItem(nameTokens, "total"), "total") } // Append _ratio for metrics with unit "1" // Some OTel receivers improperly use unit "1" for counters of objects // See https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aissue+some+metric+units+don%27t+follow+otel+semantic+conventions // Until these issues have been fixed, we're appending `_ratio` for gauges ONLY // Theoretically, counters could be ratios as well, but it's absurd (for mathematical reasons) if unit == "1" && metricType == MetricTypeGauge { nameTokens = append(removeItem(nameTokens, "ratio"), "ratio") } // Namespace? if namespace != "" { nameTokens = append([]string{namespace}, nameTokens...) } // Build the string from the tokens, separated with underscores normalizedName := strings.Join(nameTokens, "_") // Metric name cannot start with a digit, so prefix it with "_" in this case if normalizedName != "" && unicode.IsDigit(rune(normalizedName[0])) { normalizedName = "_" + normalizedName } return normalizedName } // addUnitTokens will add the suffixes to the nameTokens if they are not already present. // It will also remove trailing underscores from the main suffix to avoid double underscores // when joining the tokens. // // If the 'per' unit ends with underscore, the underscore will be removed. If the per unit is just // 'per_', it will be entirely removed. func addUnitTokens(nameTokens []string, mainUnitSuffix, perUnitSuffix string) []string { if slices.Contains(nameTokens, mainUnitSuffix) { mainUnitSuffix = "" } if perUnitSuffix == "per_" { perUnitSuffix = "" } else { perUnitSuffix = strings.TrimSuffix(perUnitSuffix, "_") if slices.Contains(nameTokens, perUnitSuffix) { perUnitSuffix = "" } } if perUnitSuffix != "" { mainUnitSuffix = strings.TrimSuffix(mainUnitSuffix, "_") } if mainUnitSuffix != "" { nameTokens = append(nameTokens, mainUnitSuffix) } if perUnitSuffix != "" { nameTokens = append(nameTokens, perUnitSuffix) } return nameTokens } // Remove the specified value from the slice. func removeItem(slice []string, value string) []string { newSlice := make([]string, 0, len(slice)) for _, sliceEntry := range slice { if sliceEntry != value { newSlice = append(newSlice, sliceEntry) } } return newSlice } func (mn *MetricNamer) buildMetricName(inputName, unit string, metricType MetricType) (name string, err error) { name = inputName if mn.Namespace != "" { name = mn.Namespace + "_" + name } if mn.WithMetricSuffixes { // Append _ratio for metrics with unit "1" // Some OTel receivers improperly use unit "1" for counters of objects // See https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aissue+some+metric+units+don%27t+follow+otel+semantic+conventions // Until these issues have been fixed, we're appending `_ratio` for gauges ONLY // Theoretically, counters could be ratios as well, but it's absurd (for mathematical reasons) if unit == "1" && metricType == MetricTypeGauge { name = trimSuffixAndDelimiter(name, "ratio") defer func() { name += "_ratio" }() } // Append _total for Counters. if metricType == MetricTypeMonotonicCounter { name = trimSuffixAndDelimiter(name, "total") defer func() { name += "_total" }() } mainUnitSuffix, perUnitSuffix := buildUnitSuffixes(unit) if perUnitSuffix != "" { name = trimSuffixAndDelimiter(name, perUnitSuffix) defer func() { name = name + "_" + perUnitSuffix }() } // We don't need to trim and re-append the suffix here because this is // the inner-most suffix. if mainUnitSuffix != "" && !strings.HasSuffix(name, mainUnitSuffix) { name = name + "_" + mainUnitSuffix } } return } // trimSuffixAndDelimiter trims a suffix, plus one extra character which is // assumed to be a delimiter. func trimSuffixAndDelimiter(name, suffix string) string { if strings.HasSuffix(name, suffix) && len(name) > len(suffix)+1 { return name[:len(name)-(len(suffix)+1)] } return name } golang-github-prometheus-otlptranslator-1.0.0/metric_namer_bench_test.go000066400000000000000000000044411520146734700267240ustar00rootroot00000000000000package otlptranslator import ( "fmt" "testing" ) func BenchmarkBuild(b *testing.B) { scenarios := createTestScenarios() builder := MetricNamer{Namespace: "test_namespace"} for _, withSuffixes := range []bool{true, false} { builder.WithMetricSuffixes = withSuffixes b.Run(fmt.Sprintf("withSuffixes=%t", withSuffixes), func(b *testing.B) { for _, utf8Allowed := range []bool{true, false} { builder.UTF8Allowed = utf8Allowed b.Run(fmt.Sprintf("utf8Allowed=%t", utf8Allowed), func(b *testing.B) { for _, scenario := range scenarios { b.Run(scenario.name, func(b *testing.B) { for i := 0; i < b.N; i++ { //nolint:errcheck builder.Build(scenario.metric) } }) } }) } }) } } type scenario struct { name string metric Metric } func createTestScenarios() []scenario { scenarios := make([]scenario, 0) scenarios = append(scenarios, scenario{ name: "Basic metric with no special characters", metric: Metric{ Name: "simple_metric", Unit: "", Type: MetricTypeGauge, }, }) scenarios = append(scenarios, scenario{ name: "Counter metric", metric: Metric{ Name: "counter_metric", Unit: "", Type: MetricTypeMonotonicCounter, }, }) scenarios = append(scenarios, scenario{ name: "Gauge ratio metric", metric: Metric{ Name: "ratio_metric", Unit: "1", Type: MetricTypeGauge, }, }) scenarios = append(scenarios, scenario{ name: "Metric with per-unit suffix notation", metric: Metric{ Name: "requests", Unit: "1/s", Type: MetricTypeGauge, }, }) scenarios = append(scenarios, scenario{ name: "Metric with special characters", metric: Metric{ Name: "metric@with#special$chars", Unit: "", Type: MetricTypeGauge, }, }) scenarios = append(scenarios, scenario{ name: "Metric starting with digit", metric: Metric{ Name: "123metric", Unit: "", Type: MetricTypeGauge, }, }) scenarios = append(scenarios, scenario{ name: "Metric with multiple underscores", metric: Metric{ Name: "metric__with__multiple__underscores", Unit: "", Type: MetricTypeGauge, }, }) scenarios = append(scenarios, scenario{ name: "Metric with complex unit", metric: Metric{ Name: "memory_usage", Unit: "MiBy/s", Type: MetricTypeGauge, }, }) return scenarios } golang-github-prometheus-otlptranslator-1.0.0/metric_namer_test.go000066400000000000000000000705201520146734700255660ustar00rootroot00000000000000// Copyright 2025 The Prometheus 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. // Provenance-includes-location: https://github.com/prometheus/prometheus/blob/93e991ef7ed19cc997a9360c8016cac3767b8057/storage/remote/otlptranslator/prometheus/metric_name_builder_test.go // Provenance-includes-license: Apache-2.0 // Provenance-includes-copyright: Copyright The Prometheus Authors // Provenance-includes-location: https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/95e8f8fdc2a9dc87230406c9a3cf02be4fd68bea/pkg/translator/prometheus/normalize_name_test.go // Provenance-includes-license: Apache-2.0 // Provenance-includes-copyright: Copyright The OpenTelemetry Authors. package otlptranslator import ( "strings" "testing" ) func TestMetricNamer_Build(t *testing.T) { tests := []struct { name string namer MetricNamer metric Metric wantMetricName string wantUnitName string wantError string }{ // UTF8Allowed = false, WithMetricSuffixes = false tests { name: "simple metric name without suffixes", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: false, }, metric: Metric{ Name: "simple_metric", Unit: "", Type: MetricTypeGauge, }, wantMetricName: "simple_metric", }, { name: "metric with special characters replaced", namer: NewMetricNamer("", UnderscoreEscapingWithoutSuffixes), metric: Metric{ Name: "metric@with#special$chars", Unit: "", Type: MetricTypeGauge, }, wantMetricName: "metric_with_special_chars", }, { name: "metric starting with digit gets underscore prefix", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: false, }, metric: Metric{ Name: "123metric", Unit: "", Type: MetricTypeGauge, }, wantMetricName: "_123metric", }, { name: "metric with namespace without suffixes", namer: MetricNamer{ Namespace: "test_namespace", UTF8Allowed: false, WithMetricSuffixes: false, }, metric: Metric{ Name: "simple_metric", Unit: "", Type: MetricTypeGauge, }, wantMetricName: "test_namespace_simple_metric", }, { name: "empty metric name without suffixes", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: false, }, metric: Metric{ Name: "", Unit: "", Type: MetricTypeGauge, }, wantMetricName: "", wantError: "normalization for metric \"\" resulted in empty name", }, { name: "metric with multiple consecutive special chars", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: false, }, metric: Metric{ Name: "metric@@##$$name", Unit: "", Type: MetricTypeGauge, }, wantMetricName: "metric_name", }, { name: "metric name with only special characters", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: false, }, metric: Metric{ Name: "@#$%", Unit: "", Type: MetricTypeGauge, }, wantError: "normalization for metric \"@#$%\" resulted in empty name", }, { name: "metric name with only special characters", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: false, }, metric: Metric{ Name: "@_#_$_%", Unit: "", Type: MetricTypeGauge, }, wantError: "normalization for metric \"@_#_$_%\" resulted in invalid name \"_____\"", }, { name: "namespace with special characters", namer: NewMetricNamer("test@namespace!!??", UnderscoreEscapingWithoutSuffixes), metric: Metric{ Name: "metric", Unit: "", Type: MetricTypeGauge, }, wantMetricName: "test_namespace_metric", }, // UTF8Allowed = false, WithMetricSuffixes = true tests { name: "counter metric with total suffix", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "requests", Unit: "", Type: MetricTypeMonotonicCounter, }, wantMetricName: "requests_total", }, { name: "gauge with unit 1 gets ratio suffix", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "cpu_usage", Unit: "1", Type: MetricTypeGauge, }, wantMetricName: "cpu_usage_ratio", }, { name: "counter with unit 1 does not get ratio suffix", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "items", Unit: "1", Type: MetricTypeMonotonicCounter, }, wantMetricName: "items_total", }, { name: "metric with time unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "response_time", Unit: "ms", Type: MetricTypeGauge, }, wantMetricName: "response_time_milliseconds", wantUnitName: "milliseconds", }, { name: "metric with bytes unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "memory_usage", Unit: "By", Type: MetricTypeGauge, }, wantMetricName: "memory_usage_bytes", wantUnitName: "bytes", }, { name: "metric with per unit", namer: NewMetricNamer("", UnderscoreEscapingWithSuffixes), metric: Metric{ Name: "requests", Unit: "1/s", Type: MetricTypeGauge, }, wantMetricName: "requests_per_second", wantUnitName: "per_second", }, { name: "metric with complex per unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "throughput", Unit: "By/s", Type: MetricTypeGauge, }, wantMetricName: "throughput_bytes_per_second", wantUnitName: "bytes_per_second", }, { name: "metric with unknown unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "custom_metric", Unit: "custom_unit", Type: MetricTypeGauge, }, wantMetricName: "custom_metric_custom_unit", wantUnitName: "custom_unit", }, { name: "metric with unit containing braces is ignored", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "custom_metric", Unit: "{custom}", Type: MetricTypeGauge, }, wantMetricName: "custom_metric", }, { name: "metric with per unit containing braces is ignored", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "custom_metric", Unit: "By/{custom}", Type: MetricTypeGauge, }, wantMetricName: "custom_metric_bytes", wantUnitName: "bytes", }, { name: "metric name already contains total suffix", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "requests_total", Unit: "", Type: MetricTypeMonotonicCounter, }, wantMetricName: "requests_total", }, { name: "metric name already contains ratio suffix", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "cpu_usage_ratio", Unit: "1", Type: MetricTypeGauge, }, wantMetricName: "cpu_usage_ratio", }, { name: "metric name already contains unit suffix", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "response_time_seconds", Unit: "s", Type: MetricTypeGauge, }, wantMetricName: "response_time_seconds", wantUnitName: "seconds", }, { name: "metric name already contains total suffix with UTF8Allowed", namer: MetricNamer{ UTF8Allowed: true, WithMetricSuffixes: true, }, metric: Metric{ Name: "requests_total", Unit: "", Type: MetricTypeMonotonicCounter, }, wantMetricName: "requests_total", }, { name: "metric name already contains ratio suffix with UTF8Allowed", namer: MetricNamer{ UTF8Allowed: true, WithMetricSuffixes: true, }, metric: Metric{ Name: "cpu_usage_ratio", Unit: "1", Type: MetricTypeGauge, }, wantMetricName: "cpu_usage_ratio", }, { name: "metric name already contains unit suffix with UTF8Allowed", namer: MetricNamer{ UTF8Allowed: true, WithMetricSuffixes: true, }, metric: Metric{ Name: "response_time_seconds", Unit: "s", Type: MetricTypeGauge, }, wantMetricName: "response_time_seconds", wantUnitName: "seconds", }, { name: "metric name already contains type and unit suffix with UTF8Allowed", namer: MetricNamer{ UTF8Allowed: true, WithMetricSuffixes: true, }, metric: Metric{ Name: "cpu_seconds_total", Unit: "s", Type: MetricTypeMonotonicCounter, }, wantMetricName: "cpu_seconds_total", wantUnitName: "seconds", }, { name: "reproduction case for opentelemetry-collector metrics", namer: MetricNamer{ UTF8Allowed: true, WithMetricSuffixes: true, }, metric: Metric{ Name: "otelcol_process_cpu_seconds", Unit: "s", Type: MetricTypeMonotonicCounter, }, wantMetricName: "otelcol_process_cpu_seconds_total", wantUnitName: "seconds", }, { name: "metric with namespace and suffixes", namer: MetricNamer{ Namespace: "app", UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "requests", Unit: "1/s", Type: MetricTypeMonotonicCounter, }, wantMetricName: "app_requests_per_second_total", wantUnitName: "per_second", }, { name: "metric starting with digit with namespace and suffixes", namer: MetricNamer{ Namespace: "app", UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "123_requests", Unit: "", Type: MetricTypeMonotonicCounter, }, wantMetricName: "app_123_requests_total", }, { name: "metric with only underscores (escaped)", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: false, }, metric: Metric{ Name: "___", Unit: "", Type: MetricTypeGauge, }, wantMetricName: "___", }, { name: "metric with only underscores (utf8)", namer: MetricNamer{ UTF8Allowed: true, WithMetricSuffixes: false, }, metric: Metric{ Name: "___", Unit: "", Type: MetricTypeGauge, }, wantMetricName: "___", }, { name: "metric with multiple underscores normalized", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "metric__with__multiple__underscores", Unit: "unit__multiple__underscores", Type: MetricTypeGauge, }, wantMetricName: "metric_with_multiple_underscores_unit_multiple_underscores", wantUnitName: "unit_multiple_underscores", }, { name: "metric with special chars in unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "custom_metric", Unit: "unit@with#special/chars", Type: MetricTypeGauge, }, wantMetricName: "custom_metric_unit_with_special_per_chars", wantUnitName: "unit_with_special_per_chars", }, { name: "metric name with only special characters", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "@#$%", Unit: "", Type: MetricTypeGauge, }, wantMetricName: "", wantError: "normalization for metric \"@#$%\" resulted in empty name", }, // UTF8Allowed = true, WithMetricSuffixes = false tests { name: "utf8 metric without suffixes", namer: MetricNamer{ UTF8Allowed: true, WithMetricSuffixes: false, }, metric: Metric{ Name: "métric_with_ñ_chars", Unit: "", Type: MetricTypeGauge, }, wantMetricName: "métric_with_ñ_chars", }, { name: "utf8 metric with namespace without suffixes", namer: NewMetricNamer("test_namespace", NoTranslation), metric: Metric{ Name: "métric_with_ñ_chars", Unit: "", Type: MetricTypeGauge, }, wantMetricName: "test_namespace_métric_with_ñ_chars", }, // UTF8Allowed = true, WithMetricSuffixes = true tests { name: "utf8 counter metric with total suffix", namer: MetricNamer{ UTF8Allowed: true, WithMetricSuffixes: true, }, metric: Metric{ Name: "requêsts", Unit: "", Type: MetricTypeMonotonicCounter, }, wantMetricName: "requêsts_total", }, { name: "utf8 gauge with unit 1 gets ratio suffix", namer: MetricNamer{ UTF8Allowed: true, WithMetricSuffixes: true, }, metric: Metric{ Name: "cpu_usagé", Unit: "1", Type: MetricTypeGauge, }, wantMetricName: "cpu_usagé_ratio", }, { name: "utf8 metric with time unit", namer: MetricNamer{ UTF8Allowed: true, WithMetricSuffixes: true, }, metric: Metric{ Name: "respønse_time", Unit: "ms", Type: MetricTypeGauge, }, wantMetricName: "respønse_time_milliseconds", wantUnitName: "milliseconds", }, { name: "utf8 metric with per unit", namer: MetricNamer{ UTF8Allowed: true, WithMetricSuffixes: true, }, metric: Metric{ Name: "requêsts", Unit: "1/s", Type: MetricTypeGauge, }, wantMetricName: "requêsts_per_second", wantUnitName: "per_second", }, { name: "utf8 metric with namespace and suffixes", namer: NewMetricNamer("ñamespace", NoUTF8EscapingWithSuffixes), metric: Metric{ Name: "requêsts", Unit: "1/s", Type: MetricTypeMonotonicCounter, }, wantMetricName: "ñamespace_requêsts_per_second_total", wantUnitName: "per_second", }, { name: "metric name with only special characters", namer: MetricNamer{ UTF8Allowed: true, WithMetricSuffixes: true, }, metric: Metric{ Name: "@#$%", Unit: "", Type: MetricTypeMonotonicCounter, }, wantMetricName: "@#$%_total", }, { name: "namespace with special characters", namer: MetricNamer{ Namespace: "test@namespace", UTF8Allowed: true, WithMetricSuffixes: true, }, metric: Metric{ Name: "metric", Unit: "", Type: MetricTypeMonotonicCounter, }, wantMetricName: "test@namespace_metric_total", }, // Edge cases and different metric types { name: "histogram metric type", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "request_duration", Unit: "s", Type: MetricTypeHistogram, }, wantMetricName: "request_duration_seconds", wantUnitName: "seconds", }, { name: "exponential histogram metric type", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "request_size", Unit: "By", Type: MetricTypeExponentialHistogram, }, wantMetricName: "request_size_bytes", wantUnitName: "bytes", }, { name: "summary metric type", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "response_time", Unit: "ms", Type: MetricTypeSummary, }, wantMetricName: "response_time_milliseconds", wantUnitName: "milliseconds", }, { name: "non-monotonic counter metric type", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "active_connections", Unit: "", Type: MetricTypeNonMonotonicCounter, }, wantMetricName: "active_connections", }, { name: "unknown metric type", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "unknown_metric", Unit: "", Type: MetricTypeUnknown, }, wantMetricName: "unknown_metric", }, // Additional unit mapping tests { name: "metric with days unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "uptime", Unit: "d", Type: MetricTypeGauge, }, wantMetricName: "uptime_days", wantUnitName: "days", }, { name: "metric with hours unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "duration", Unit: "h", Type: MetricTypeGauge, }, wantMetricName: "duration_hours", wantUnitName: "hours", }, { name: "metric with minutes unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "timeout", Unit: "min", Type: MetricTypeGauge, }, wantMetricName: "timeout_minutes", wantUnitName: "minutes", }, { name: "metric with microseconds unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "latency", Unit: "us", Type: MetricTypeGauge, }, wantMetricName: "latency_microseconds", wantUnitName: "microseconds", }, { name: "metric with nanoseconds unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "precision_time", Unit: "ns", Type: MetricTypeGauge, }, wantMetricName: "precision_time_nanoseconds", wantUnitName: "nanoseconds", }, { name: "metric with kibibytes unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "cache_size", Unit: "KiBy", Type: MetricTypeGauge, }, wantMetricName: "cache_size_kibibytes", wantUnitName: "kibibytes", }, { name: "metric with mebibytes unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "memory", Unit: "MiBy", Type: MetricTypeGauge, }, wantMetricName: "memory_mebibytes", wantUnitName: "mebibytes", }, { name: "metric with gibibytes unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "storage", Unit: "GiBy", Type: MetricTypeGauge, }, wantMetricName: "storage_gibibytes", wantUnitName: "gibibytes", }, { name: "metric with tibibytes unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "capacity", Unit: "TiBy", Type: MetricTypeGauge, }, wantMetricName: "capacity_tibibytes", wantUnitName: "tibibytes", }, { name: "metric with kilobytes unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "transfer", Unit: "KBy", Type: MetricTypeGauge, }, wantMetricName: "transfer_kilobytes", wantUnitName: "kilobytes", }, { name: "metric with megabytes unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "download", Unit: "MBy", Type: MetricTypeGauge, }, wantMetricName: "download_megabytes", wantUnitName: "megabytes", }, { name: "metric with gigabytes unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "backup", Unit: "GBy", Type: MetricTypeGauge, }, wantMetricName: "backup_gigabytes", wantUnitName: "gigabytes", }, { name: "metric with terabytes unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "archive", Unit: "TBy", Type: MetricTypeGauge, }, wantMetricName: "archive_terabytes", wantUnitName: "terabytes", }, { name: "metric with meters unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "distance", Unit: "m", Type: MetricTypeGauge, }, wantMetricName: "distance_meters", wantUnitName: "meters", }, { name: "metric with volts unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "voltage", Unit: "V", Type: MetricTypeGauge, }, wantMetricName: "voltage_volts", wantUnitName: "volts", }, { name: "metric with amperes unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "current", Unit: "A", Type: MetricTypeGauge, }, wantMetricName: "current_amperes", wantUnitName: "amperes", }, { name: "metric with joules unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "energy", Unit: "J", Type: MetricTypeGauge, }, wantMetricName: "energy_joules", wantUnitName: "joules", }, { name: "metric with watts unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "power", Unit: "W", Type: MetricTypeGauge, }, wantMetricName: "power_watts", wantUnitName: "watts", }, { name: "metric with grams unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "weight", Unit: "g", Type: MetricTypeGauge, }, wantMetricName: "weight_grams", wantUnitName: "grams", }, { name: "metric with celsius unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "temperature", Unit: "Cel", Type: MetricTypeGauge, }, wantMetricName: "temperature_celsius", wantUnitName: "celsius", }, { name: "metric with hertz unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "frequency", Unit: "Hz", Type: MetricTypeGauge, }, wantMetricName: "frequency_hertz", wantUnitName: "hertz", }, { name: "metric with percent unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "cpu_usage", Unit: "%", Type: MetricTypeGauge, }, wantMetricName: "cpu_usage_percent", wantUnitName: "percent", }, // Per unit mapping tests { name: "metric with per minute unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "requests", Unit: "1/m", Type: MetricTypeGauge, }, wantMetricName: "requests_per_minute", wantUnitName: "per_minute", }, { name: "metric with per hour unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "events", Unit: "1/h", Type: MetricTypeGauge, }, wantMetricName: "events_per_hour", wantUnitName: "per_hour", }, { name: "metric with per day unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "transactions", Unit: "1/d", Type: MetricTypeGauge, }, wantMetricName: "transactions_per_day", wantUnitName: "per_day", }, { name: "metric with per week unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "reports", Unit: "1/w", Type: MetricTypeGauge, }, wantMetricName: "reports_per_week", wantUnitName: "per_week", }, { name: "metric with per month unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "invoices", Unit: "1/mo", Type: MetricTypeGauge, }, wantMetricName: "invoices_per_month", wantUnitName: "per_month", }, { name: "metric with per year unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "renewals", Unit: "1/y", Type: MetricTypeGauge, }, wantMetricName: "renewals_per_year", wantUnitName: "per_year", }, { name: "metric with unknown per unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "custom", Unit: "1/custom_unit", Type: MetricTypeGauge, }, wantMetricName: "custom_per_custom_unit", wantUnitName: "per_custom_unit", }, // Edge cases with empty and whitespace units { name: "metric with empty per unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "metric", Unit: "By/", Type: MetricTypeGauge, }, wantMetricName: "metric_bytes", wantUnitName: "bytes", }, { name: "metric with whitespace in unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "metric", Unit: " By / s ", Type: MetricTypeGauge, }, wantMetricName: "metric_bytes_per_second", wantUnitName: "bytes_per_second", }, { name: "metric with only slash in unit", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "metric", Unit: "/", Type: MetricTypeGauge, }, wantMetricName: "metric", }, // Common OTel metrics to showcase how the namer works { name: "http.request.duration/Prometheus-style", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "http.request.duration", Unit: "ms", Type: MetricTypeHistogram, }, wantMetricName: "http_request_duration_milliseconds", wantUnitName: "milliseconds", }, { name: "http.request.duration/OTel-style", namer: MetricNamer{ UTF8Allowed: true, WithMetricSuffixes: false, }, metric: Metric{ Name: "http.request.duration", Unit: "ms", Type: MetricTypeHistogram, }, wantMetricName: "http.request.duration", wantUnitName: "milliseconds", }, { name: "http.requests/Prometheus-style", namer: MetricNamer{ UTF8Allowed: false, WithMetricSuffixes: true, }, metric: Metric{ Name: "http.requests", Unit: "1", Type: MetricTypeMonotonicCounter, }, wantMetricName: "http_requests_total", }, { name: "http.requests/OTel-style", namer: MetricNamer{ UTF8Allowed: true, WithMetricSuffixes: false, }, metric: Metric{ Name: "http.requests", Unit: "1", Type: MetricTypeMonotonicCounter, }, wantMetricName: "http.requests", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { // Build metric name using MetricNamer gotMetricName, err := tt.namer.Build(tt.metric) if tt.wantError != "" { if err == nil { t.Errorf("MetricNamer.Build(%v), got nil err, want %q", tt.metric, tt.wantError) } else if err.Error() != tt.wantError { t.Errorf("MetricNamer.Build(%v), got err string = %q want %q", tt.metric, err, tt.wantError) } } else if err != nil { t.Errorf("MetricNamer.Build(%v), got err string = %q want nil", tt.metric, err) } if gotMetricName != tt.wantMetricName { t.Errorf("MetricNamer.Build(%v) = %q, want %q", tt.metric, gotMetricName, tt.wantMetricName) } // Build unit name using UnitNamer to verify correlation when suffixes are enabled if tt.namer.WithMetricSuffixes { unitNamer := UnitNamer{ UTF8Allowed: tt.namer.UTF8Allowed, } gotUnitName := unitNamer.Build(tt.metric.Unit) if gotUnitName != tt.wantUnitName { t.Errorf("UnitNamer.Build(%q) = %q, want %q", tt.metric.Unit, gotUnitName, tt.wantUnitName) } // Verify correlation: if UnitNamer produces a non-empty unit name, // it should be contained in the metric name when WithMetricSuffixes=true if tt.namer.WithMetricSuffixes && !strings.Contains(gotMetricName, gotUnitName) { t.Errorf("Metric name %q should contain unit name %q when WithMetricSuffixes=true", gotMetricName, gotUnitName) } } }) } } golang-github-prometheus-otlptranslator-1.0.0/metric_type.go000066400000000000000000000031131520146734700244000ustar00rootroot00000000000000// Copyright 2025 The Prometheus 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 package otlptranslator // MetricType is a representation of metric types from OpenTelemetry. // Different types of Sums were introduced based on their metric temporalities. // For more details, see: // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/data-model.md#sums type MetricType int const ( // MetricTypeUnknown represents an unknown metric type. MetricTypeUnknown = iota // MetricTypeNonMonotonicCounter represents a counter that is not monotonically increasing, also known as delta counter. MetricTypeNonMonotonicCounter // MetricTypeMonotonicCounter represents a counter that is monotonically increasing, also known as cumulative counter. MetricTypeMonotonicCounter // MetricTypeGauge represents a gauge metric. MetricTypeGauge // MetricTypeHistogram represents a histogram metric. MetricTypeHistogram // MetricTypeExponentialHistogram represents an exponential histogram metric. MetricTypeExponentialHistogram // MetricTypeSummary represents a summary metric. MetricTypeSummary ) golang-github-prometheus-otlptranslator-1.0.0/strategy.go000066400000000000000000000100511520146734700237150ustar00rootroot00000000000000// Copyright 2025 The Prometheus 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. // Provenance-includes-location: https://github.com/prometheus/prometheus/blob/3602785a89162ccc99a940fb9d862219a2d02241/config/config.go // Provenance-includes-license: Apache-2.0 // Provenance-includes-copyright: Copyright The Prometheus Authors package otlptranslator // TranslationStrategyOption is a constant that defines how metric and label // names should be handled during translation. The recommended approach is to // use either UnderscoreEscapingWithSuffixes for full Prometheus-style // compatibility, or NoTranslation for Otel-style names. type TranslationStrategyOption string var ( // NoUTF8EscapingWithSuffixes will accept metric/label names as they are. Unit // and type suffixes may be added to metric names, according to certain rules. NoUTF8EscapingWithSuffixes TranslationStrategyOption = "NoUTF8EscapingWithSuffixes" // UnderscoreEscapingWithSuffixes is the default option for translating OTLP // to Prometheus. This option will translate metric name characters that are // not alphanumerics/underscores/colons to underscores, and label name // characters that are not alphanumerics/underscores to underscores. Unit and // type suffixes may be appended to metric names, according to certain rules. UnderscoreEscapingWithSuffixes TranslationStrategyOption = "UnderscoreEscapingWithSuffixes" // UnderscoreEscapingWithoutSuffixes translates metric name characters that // are not alphanumerics/underscores/colons to underscores, and label name // characters that are not alphanumerics/underscores to underscores, but // unlike UnderscoreEscapingWithSuffixes it does not append any suffixes to // the names. UnderscoreEscapingWithoutSuffixes TranslationStrategyOption = "UnderscoreEscapingWithoutSuffixes" // NoTranslation (EXPERIMENTAL): disables all translation of incoming metric // and label names. This offers a way for the OTLP users to use native metric // names, reducing confusion. // // WARNING: This setting has significant known risks and limitations (see // https://prometheus.io/docs/practices/naming/ for details): * Impaired UX // when using PromQL in plain YAML (e.g. alerts, rules, dashboard, autoscaling // configuration). * Series collisions which in the best case may result in // OOO errors, in the worst case a silently malformed time series. For // instance, you may end up in situation of ingesting `foo.bar` series with // unit `seconds` and a separate series `foo.bar` with unit `milliseconds`. // // As a result, this setting is experimental and currently, should not be used // in production systems. // // TODO(ArthurSens): Mention `type-and-unit-labels` feature // (https://github.com/prometheus/proposals/pull/39) once released, as // potential mitigation of the above risks. NoTranslation TranslationStrategyOption = "NoTranslation" ) // ShouldEscape returns true if the translation strategy requires that metric // names be escaped. func (o TranslationStrategyOption) ShouldEscape() bool { switch o { case UnderscoreEscapingWithSuffixes, UnderscoreEscapingWithoutSuffixes: return true case NoTranslation, NoUTF8EscapingWithSuffixes: return false default: return false } } // ShouldAddSuffixes returns a bool deciding whether the given translation // strategy should have suffixes added. func (o TranslationStrategyOption) ShouldAddSuffixes() bool { switch o { case UnderscoreEscapingWithSuffixes, NoUTF8EscapingWithSuffixes: return true case UnderscoreEscapingWithoutSuffixes, NoTranslation: return false default: return false } } golang-github-prometheus-otlptranslator-1.0.0/strconv.go000066400000000000000000000072671520146734700235700ustar00rootroot00000000000000// Copyright 2025 The Prometheus 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. // Provenance-includes-location: https://github.com/prometheus/prometheus/blob/93e991ef7ed19cc997a9360c8016cac3767b8057/storage/remote/otlptranslator/prometheus/strconv.go.go // Provenance-includes-license: Apache-2.0 // Provenance-includes-copyright: Copyright The Prometheus Authors // Provenance-includes-location: https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/95e8f8fdc2a9dc87230406c9a3cf02be4fd68bea/pkg/translator/prometheus/normalize_name_test.go // Provenance-includes-license: Apache-2.0 // Provenance-includes-copyright: Copyright The OpenTelemetry Authors. package otlptranslator import ( "strings" ) // sanitizeLabelName replaces any characters not valid according to the // classical Prometheus label naming scheme with an underscore. // When preserveMultipleUnderscores is true, multiple consecutive underscores are preserved. // When false, multiple consecutive underscores are collapsed to a single underscore. func sanitizeLabelName(name string, preserveMultipleUnderscores bool) string { nameLength := len(name) if preserveMultipleUnderscores { // Simple case: just replace invalid characters, preserve multiple underscores var b strings.Builder b.Grow(nameLength) for _, r := range name { if isValidCompliantLabelChar(r) { b.WriteRune(r) } else { b.WriteRune('_') } } return b.String() } isReserved, labelName := isReservedLabel(name) if isReserved { name = labelName } // Collapse multiple underscores while replacing invalid characters. var b strings.Builder b.Grow(nameLength) prevWasUnderscore := false for _, r := range name { if isValidCompliantLabelChar(r) { b.WriteRune(r) prevWasUnderscore = false } else if !prevWasUnderscore { // Invalid character - replace with underscore. b.WriteRune('_') prevWasUnderscore = true } } if isReserved { return "__" + b.String() + "__" } return b.String() } // isValidCompliantLabelChar checks if a rune is a valid label name character (a-z, A-Z, 0-9). func isValidCompliantLabelChar(r rune) bool { return (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') } // isReservedLabel checks if a label is a reserved label. // Reserved labels are labels that start and end with exactly __. // The returned label name is the label name without the __ prefix and suffix. func isReservedLabel(name string) (bool, string) { if len(name) < 4 { return false, "" } if !strings.HasPrefix(name, "__") || !strings.HasSuffix(name, "__") { return false, "" } return true, name[2 : len(name)-2] } // collapseMultipleUnderscores replaces multiple consecutive underscores with a single underscore. // This is equivalent to regexp.MustCompile(`__+`).ReplaceAllString(s, "_") but without using regex. func collapseMultipleUnderscores(s string) string { if len(s) == 0 { return s } var b strings.Builder b.Grow(len(s)) prevWasUnderscore := false for _, r := range s { if r == '_' { if !prevWasUnderscore { b.WriteRune('_') prevWasUnderscore = true } // Skip consecutive underscores } else { b.WriteRune(r) prevWasUnderscore = false } } return b.String() } golang-github-prometheus-otlptranslator-1.0.0/unit_namer.go000066400000000000000000000103651520146734700242240ustar00rootroot00000000000000// Copyright 2025 The Prometheus 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 package otlptranslator import "strings" // UnitNamer is a helper for building compliant unit names. // It processes OpenTelemetry Protocol (OTLP) unit strings and converts them // to Prometheus-compliant unit names. // // Example usage: // // namer := UnitNamer{UTF8Allowed: false} // result := namer.Build("s") // "seconds" // result = namer.Build("By/s") // "bytes_per_second" type UnitNamer struct { UTF8Allowed bool } // Build builds a unit name for the specified unit string. // It processes the unit by splitting it into main and per components, // applying unit mappings, and cleaning up invalid characters when UTF8Allowed is false. // // Unit mappings include: // - Time: s→seconds, ms→milliseconds, h→hours // - Bytes: By→bytes, KBy→kilobytes, MBy→megabytes // - SI: m→meters, V→volts, W→watts // - Special: 1→"" (empty), %→percent // // Examples: // // namer := UnitNamer{UTF8Allowed: false} // namer.Build("s") // "seconds" // namer.Build("requests/s") // "requests_per_second" // namer.Build("1") // "" (dimensionless) func (un *UnitNamer) Build(unit string) string { mainUnit, perUnit := buildUnitSuffixes(unit) if !un.UTF8Allowed { mainUnit, perUnit = cleanUpUnit(mainUnit), cleanUpUnit(perUnit) } var u string switch { case mainUnit != "" && perUnit != "": u = mainUnit + "_" + perUnit case mainUnit != "": u = mainUnit default: u = perUnit } // Clean up leading and trailing underscores if len(u) > 0 && u[0:1] == "_" { u = u[1:] } if len(u) > 0 && u[len(u)-1:] == "_" { u = u[:len(u)-1] } return u } // Retrieve the Prometheus "basic" unit corresponding to the specified "basic" unit. // Returns the specified unit if not found in unitMap. func unitMapGetOrDefault(unit string) string { if promUnit, ok := unitMap[unit]; ok { return promUnit } return unit } // Retrieve the Prometheus "per" unit corresponding to the specified "per" unit. // Returns the specified unit if not found in perUnitMap. func perUnitMapGetOrDefault(perUnit string) string { if promPerUnit, ok := perUnitMap[perUnit]; ok { return promPerUnit } return perUnit } // buildUnitSuffixes builds the main and per unit suffixes for the specified unit // but doesn't do any special character transformation to accommodate Prometheus naming conventions. // Removing trailing underscores or appending suffixes is done in the caller. func buildUnitSuffixes(unit string) (mainUnitSuffix, perUnitSuffix string) { // Split unit at the '/' if any unitTokens := strings.SplitN(unit, "/", 2) if len(unitTokens) > 0 { // Main unit // Update if not blank and doesn't contain '{}' mainUnitOTel := strings.TrimSpace(unitTokens[0]) if mainUnitOTel != "" && !strings.ContainsAny(mainUnitOTel, "{}") { mainUnitSuffix = unitMapGetOrDefault(mainUnitOTel) } // Per unit // Update if not blank and doesn't contain '{}' if len(unitTokens) > 1 && unitTokens[1] != "" { perUnitOTel := strings.TrimSpace(unitTokens[1]) if perUnitOTel != "" && !strings.ContainsAny(perUnitOTel, "{}") { perUnitSuffix = perUnitMapGetOrDefault(perUnitOTel) } if perUnitSuffix != "" { perUnitSuffix = "per_" + perUnitSuffix } } } return mainUnitSuffix, perUnitSuffix } // cleanUpUnit cleans up unit so it matches model.LabelNameRE. func cleanUpUnit(unit string) string { // Multiple consecutive underscores are replaced with a single underscore. // This is part of the OTel to Prometheus specification: https://github.com/open-telemetry/opentelemetry-specification/blob/v1.38.0/specification/compatibility/prometheus_and_openmetrics.md#otlp-metric-points-to-prometheus. return strings.TrimPrefix(collapseMultipleUnderscores( strings.Map(replaceInvalidMetricChar, unit), ), "_") }