diff options
Diffstat (limited to 'vendor/go.opentelemetry.io/otel/exporters/prometheus')
5 files changed, 0 insertions, 924 deletions
diff --git a/vendor/go.opentelemetry.io/otel/exporters/prometheus/LICENSE b/vendor/go.opentelemetry.io/otel/exporters/prometheus/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/go.opentelemetry.io/otel/exporters/prometheus/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - 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. diff --git a/vendor/go.opentelemetry.io/otel/exporters/prometheus/README.md b/vendor/go.opentelemetry.io/otel/exporters/prometheus/README.md deleted file mode 100644 index f4dc09d38..000000000 --- a/vendor/go.opentelemetry.io/otel/exporters/prometheus/README.md +++ /dev/null @@ -1,3 +0,0 @@ -# Prometheus Exporter - -[](https://pkg.go.dev/go.opentelemetry.io/otel/exporters/prometheus) diff --git a/vendor/go.opentelemetry.io/otel/exporters/prometheus/config.go b/vendor/go.opentelemetry.io/otel/exporters/prometheus/config.go deleted file mode 100644 index 660675dd6..000000000 --- a/vendor/go.opentelemetry.io/otel/exporters/prometheus/config.go +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package prometheus // import "go.opentelemetry.io/otel/exporters/prometheus" - -import ( - "strings" - - "github.com/prometheus/client_golang/prometheus" - "github.com/prometheus/common/model" - - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/sdk/metric" -) - -// config contains options for the exporter. -type config struct { - registerer prometheus.Registerer - disableTargetInfo bool - withoutUnits bool - withoutCounterSuffixes bool - readerOpts []metric.ManualReaderOption - disableScopeInfo bool - namespace string - resourceAttributesFilter attribute.Filter -} - -// newConfig creates a validated config configured with options. -func newConfig(opts ...Option) config { - cfg := config{} - for _, opt := range opts { - cfg = opt.apply(cfg) - } - - if cfg.registerer == nil { - cfg.registerer = prometheus.DefaultRegisterer - } - - return cfg -} - -// Option sets exporter option values. -type Option interface { - apply(config) config -} - -type optionFunc func(config) config - -func (fn optionFunc) apply(cfg config) config { - return fn(cfg) -} - -// WithRegisterer configures which prometheus Registerer the Exporter will -// register with. If no registerer is used the prometheus DefaultRegisterer is -// used. -func WithRegisterer(reg prometheus.Registerer) Option { - return optionFunc(func(cfg config) config { - cfg.registerer = reg - return cfg - }) -} - -// WithAggregationSelector configure the Aggregation Selector the exporter will -// use. If no AggregationSelector is provided the DefaultAggregationSelector is -// used. -func WithAggregationSelector(agg metric.AggregationSelector) Option { - return optionFunc(func(cfg config) config { - cfg.readerOpts = append(cfg.readerOpts, metric.WithAggregationSelector(agg)) - return cfg - }) -} - -// WithProducer configure the metric Producer the exporter will use as a source -// of external metric data. -func WithProducer(producer metric.Producer) Option { - return optionFunc(func(cfg config) config { - cfg.readerOpts = append(cfg.readerOpts, metric.WithProducer(producer)) - return cfg - }) -} - -// WithoutTargetInfo configures the Exporter to not export the resource target_info metric. -// If not specified, the Exporter will create a target_info metric containing -// the metrics' resource.Resource attributes. -func WithoutTargetInfo() Option { - return optionFunc(func(cfg config) config { - cfg.disableTargetInfo = true - return cfg - }) -} - -// WithoutUnits disables exporter's addition of unit suffixes to metric names, -// and will also prevent unit comments from being added in OpenMetrics once -// unit comments are supported. -// -// By default, metric names include a unit suffix to follow Prometheus naming -// conventions. For example, the counter metric request.duration, with unit -// milliseconds would become request_duration_milliseconds_total. -// With this option set, the name would instead be request_duration_total. -func WithoutUnits() Option { - return optionFunc(func(cfg config) config { - cfg.withoutUnits = true - return cfg - }) -} - -// WithoutCounterSuffixes disables exporter's addition _total suffixes on counters. -// -// By default, metric names include a _total suffix to follow Prometheus naming -// conventions. For example, the counter metric happy.people would become -// happy_people_total. With this option set, the name would instead be -// happy_people. -func WithoutCounterSuffixes() Option { - return optionFunc(func(cfg config) config { - cfg.withoutCounterSuffixes = true - return cfg - }) -} - -// WithoutScopeInfo configures the Exporter to not export the otel_scope_info metric. -// If not specified, the Exporter will create a otel_scope_info metric containing -// the metrics' Instrumentation Scope, and also add labels about Instrumentation Scope to all metric points. -func WithoutScopeInfo() Option { - return optionFunc(func(cfg config) config { - cfg.disableScopeInfo = true - return cfg - }) -} - -// WithNamespace configures the Exporter to prefix metric with the given namespace. -// Metadata metrics such as target_info and otel_scope_info are not prefixed since these -// have special behavior based on their name. -func WithNamespace(ns string) Option { - return optionFunc(func(cfg config) config { - if model.NameValidationScheme != model.UTF8Validation { - // Only sanitize if prometheus does not support UTF-8. - ns = model.EscapeName(ns, model.NameEscapingScheme) - } - if !strings.HasSuffix(ns, "_") { - // namespace and metric names should be separated with an underscore, - // adds a trailing underscore if there is not one already. - ns = ns + "_" - } - - cfg.namespace = ns - return cfg - }) -} - -// WithResourceAsConstantLabels configures the Exporter to add the resource attributes the -// resourceFilter returns true for as attributes on all exported metrics. -// -// The does not affect the target info generated from resource attributes. -func WithResourceAsConstantLabels(resourceFilter attribute.Filter) Option { - return optionFunc(func(cfg config) config { - cfg.resourceAttributesFilter = resourceFilter - return cfg - }) -} diff --git a/vendor/go.opentelemetry.io/otel/exporters/prometheus/doc.go b/vendor/go.opentelemetry.io/otel/exporters/prometheus/doc.go deleted file mode 100644 index e9b77869e..000000000 --- a/vendor/go.opentelemetry.io/otel/exporters/prometheus/doc.go +++ /dev/null @@ -1,7 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -// Package prometheus provides a Prometheus Exporter that converts -// OTLP metrics into the Prometheus exposition format and implements -// prometheus.Collector to provide a handler for these metrics. -package prometheus // import "go.opentelemetry.io/otel/exporters/prometheus" diff --git a/vendor/go.opentelemetry.io/otel/exporters/prometheus/exporter.go b/vendor/go.opentelemetry.io/otel/exporters/prometheus/exporter.go deleted file mode 100644 index 50c95a16f..000000000 --- a/vendor/go.opentelemetry.io/otel/exporters/prometheus/exporter.go +++ /dev/null @@ -1,554 +0,0 @@ -// Copyright The OpenTelemetry Authors -// SPDX-License-Identifier: Apache-2.0 - -package prometheus // import "go.opentelemetry.io/otel/exporters/prometheus" - -import ( - "context" - "encoding/hex" - "errors" - "fmt" - "slices" - "strings" - "sync" - - "github.com/prometheus/client_golang/prometheus" - dto "github.com/prometheus/client_model/go" - "github.com/prometheus/common/model" - "google.golang.org/protobuf/proto" - - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/internal/global" - "go.opentelemetry.io/otel/sdk/instrumentation" - "go.opentelemetry.io/otel/sdk/metric" - "go.opentelemetry.io/otel/sdk/metric/metricdata" - "go.opentelemetry.io/otel/sdk/resource" -) - -const ( - targetInfoMetricName = "target_info" - targetInfoDescription = "Target metadata" - - scopeInfoMetricName = "otel_scope_info" - scopeInfoDescription = "Instrumentation Scope metadata" - - scopeNameLabel = "otel_scope_name" - scopeVersionLabel = "otel_scope_version" - - traceIDExemplarKey = "trace_id" - spanIDExemplarKey = "span_id" -) - -var errScopeInvalid = errors.New("invalid scope") - -// Exporter is a Prometheus Exporter that embeds the OTel metric.Reader -// interface for easy instantiation with a MeterProvider. -type Exporter struct { - metric.Reader -} - -// MarshalLog returns logging data about the Exporter. -func (e *Exporter) MarshalLog() interface{} { - const t = "Prometheus exporter" - - if r, ok := e.Reader.(*metric.ManualReader); ok { - under := r.MarshalLog() - if data, ok := under.(struct { - Type string - Registered bool - Shutdown bool - }); ok { - data.Type = t - return data - } - } - - return struct{ Type string }{Type: t} -} - -var _ metric.Reader = &Exporter{} - -// keyVals is used to store resource attribute key value pairs. -type keyVals struct { - keys []string - vals []string -} - -// collector is used to implement prometheus.Collector. -type collector struct { - reader metric.Reader - - withoutUnits bool - withoutCounterSuffixes bool - disableScopeInfo bool - namespace string - resourceAttributesFilter attribute.Filter - - mu sync.Mutex // mu protects all members below from the concurrent access. - disableTargetInfo bool - targetInfo prometheus.Metric - scopeInfos map[instrumentation.Scope]prometheus.Metric - scopeInfosInvalid map[instrumentation.Scope]struct{} - metricFamilies map[string]*dto.MetricFamily - resourceKeyVals keyVals -} - -// prometheus counters MUST have a _total suffix by default: -// https://github.com/open-telemetry/opentelemetry-specification/blob/v1.20.0/specification/compatibility/prometheus_and_openmetrics.md -const counterSuffix = "_total" - -// New returns a Prometheus Exporter. -func New(opts ...Option) (*Exporter, error) { - cfg := newConfig(opts...) - - // this assumes that the default temporality selector will always return cumulative. - // we only support cumulative temporality, so building our own reader enforces this. - // TODO (#3244): Enable some way to configure the reader, but not change temporality. - reader := metric.NewManualReader(cfg.readerOpts...) - - collector := &collector{ - reader: reader, - disableTargetInfo: cfg.disableTargetInfo, - withoutUnits: cfg.withoutUnits, - withoutCounterSuffixes: cfg.withoutCounterSuffixes, - disableScopeInfo: cfg.disableScopeInfo, - scopeInfos: make(map[instrumentation.Scope]prometheus.Metric), - scopeInfosInvalid: make(map[instrumentation.Scope]struct{}), - metricFamilies: make(map[string]*dto.MetricFamily), - namespace: cfg.namespace, - resourceAttributesFilter: cfg.resourceAttributesFilter, - } - - if err := cfg.registerer.Register(collector); err != nil { - return nil, fmt.Errorf("cannot register the collector: %w", err) - } - - e := &Exporter{ - Reader: reader, - } - - return e, nil -} - -// Describe implements prometheus.Collector. -func (c *collector) Describe(ch chan<- *prometheus.Desc) { - // The Opentelemetry SDK doesn't have information on which will exist when the collector - // is registered. By returning nothing we are an "unchecked" collector in Prometheus, - // and assume responsibility for consistency of the metrics produced. - // - // See https://pkg.go.dev/github.com/prometheus/client_golang@v1.13.0/prometheus#hdr-Custom_Collectors_and_constant_Metrics -} - -// Collect implements prometheus.Collector. -// -// This method is safe to call concurrently. -func (c *collector) Collect(ch chan<- prometheus.Metric) { - // TODO (#3047): Use a sync.Pool instead of allocating metrics every Collect. - metrics := metricdata.ResourceMetrics{} - err := c.reader.Collect(context.TODO(), &metrics) - if err != nil { - if errors.Is(err, metric.ErrReaderShutdown) { - return - } - otel.Handle(err) - if errors.Is(err, metric.ErrReaderNotRegistered) { - return - } - } - - global.Debug("Prometheus exporter export", "Data", metrics) - - // Initialize (once) targetInfo and disableTargetInfo. - func() { - c.mu.Lock() - defer c.mu.Unlock() - - if c.targetInfo == nil && !c.disableTargetInfo { - targetInfo, err := createInfoMetric(targetInfoMetricName, targetInfoDescription, metrics.Resource) - if err != nil { - // If the target info metric is invalid, disable sending it. - c.disableTargetInfo = true - otel.Handle(err) - return - } - - c.targetInfo = targetInfo - } - }() - - if !c.disableTargetInfo { - ch <- c.targetInfo - } - - if c.resourceAttributesFilter != nil && len(c.resourceKeyVals.keys) == 0 { - c.createResourceAttributes(metrics.Resource) - } - - for _, scopeMetrics := range metrics.ScopeMetrics { - n := len(c.resourceKeyVals.keys) + 2 // resource attrs + scope name + scope version - kv := keyVals{ - keys: make([]string, 0, n), - vals: make([]string, 0, n), - } - - if !c.disableScopeInfo { - scopeInfo, err := c.scopeInfo(scopeMetrics.Scope) - if errors.Is(err, errScopeInvalid) { - // Do not report the same error multiple times. - continue - } - if err != nil { - otel.Handle(err) - continue - } - - ch <- scopeInfo - - kv.keys = append(kv.keys, scopeNameLabel, scopeVersionLabel) - kv.vals = append(kv.vals, scopeMetrics.Scope.Name, scopeMetrics.Scope.Version) - } - - kv.keys = append(kv.keys, c.resourceKeyVals.keys...) - kv.vals = append(kv.vals, c.resourceKeyVals.vals...) - - for _, m := range scopeMetrics.Metrics { - typ := c.metricType(m) - if typ == nil { - continue - } - name := c.getName(m, typ) - - drop, help := c.validateMetrics(name, m.Description, typ) - if drop { - continue - } - - if help != "" { - m.Description = help - } - - switch v := m.Data.(type) { - case metricdata.Histogram[int64]: - addHistogramMetric(ch, v, m, name, kv) - case metricdata.Histogram[float64]: - addHistogramMetric(ch, v, m, name, kv) - case metricdata.Sum[int64]: - addSumMetric(ch, v, m, name, kv) - case metricdata.Sum[float64]: - addSumMetric(ch, v, m, name, kv) - case metricdata.Gauge[int64]: - addGaugeMetric(ch, v, m, name, kv) - case metricdata.Gauge[float64]: - addGaugeMetric(ch, v, m, name, kv) - } - } - } -} - -func addHistogramMetric[N int64 | float64](ch chan<- prometheus.Metric, histogram metricdata.Histogram[N], m metricdata.Metrics, name string, kv keyVals) { - for _, dp := range histogram.DataPoints { - keys, values := getAttrs(dp.Attributes) - keys = append(keys, kv.keys...) - values = append(values, kv.vals...) - - desc := prometheus.NewDesc(name, m.Description, keys, nil) - buckets := make(map[float64]uint64, len(dp.Bounds)) - - cumulativeCount := uint64(0) - for i, bound := range dp.Bounds { - cumulativeCount += dp.BucketCounts[i] - buckets[bound] = cumulativeCount - } - m, err := prometheus.NewConstHistogram(desc, dp.Count, float64(dp.Sum), buckets, values...) - if err != nil { - otel.Handle(err) - continue - } - m = addExemplars(m, dp.Exemplars) - ch <- m - } -} - -func addSumMetric[N int64 | float64](ch chan<- prometheus.Metric, sum metricdata.Sum[N], m metricdata.Metrics, name string, kv keyVals) { - valueType := prometheus.CounterValue - if !sum.IsMonotonic { - valueType = prometheus.GaugeValue - } - - for _, dp := range sum.DataPoints { - keys, values := getAttrs(dp.Attributes) - keys = append(keys, kv.keys...) - values = append(values, kv.vals...) - - desc := prometheus.NewDesc(name, m.Description, keys, nil) - m, err := prometheus.NewConstMetric(desc, valueType, float64(dp.Value), values...) - if err != nil { - otel.Handle(err) - continue - } - // GaugeValues don't support Exemplars at this time - // https://github.com/prometheus/client_golang/blob/aef8aedb4b6e1fb8ac1c90790645169125594096/prometheus/metric.go#L199 - if valueType != prometheus.GaugeValue { - m = addExemplars(m, dp.Exemplars) - } - ch <- m - } -} - -func addGaugeMetric[N int64 | float64](ch chan<- prometheus.Metric, gauge metricdata.Gauge[N], m metricdata.Metrics, name string, kv keyVals) { - for _, dp := range gauge.DataPoints { - keys, values := getAttrs(dp.Attributes) - keys = append(keys, kv.keys...) - values = append(values, kv.vals...) - - desc := prometheus.NewDesc(name, m.Description, keys, nil) - m, err := prometheus.NewConstMetric(desc, prometheus.GaugeValue, float64(dp.Value), values...) - if err != nil { - otel.Handle(err) - continue - } - ch <- m - } -} - -// getAttrs converts the attribute.Set to two lists of matching Prometheus-style -// keys and values. -func getAttrs(attrs attribute.Set) ([]string, []string) { - keys := make([]string, 0, attrs.Len()) - values := make([]string, 0, attrs.Len()) - itr := attrs.Iter() - - if model.NameValidationScheme == model.UTF8Validation { - // Do not perform sanitization if prometheus supports UTF-8. - for itr.Next() { - kv := itr.Attribute() - keys = append(keys, string(kv.Key)) - values = append(values, kv.Value.Emit()) - } - } else { - // It sanitizes invalid characters and handles duplicate keys - // (due to sanitization) by sorting and concatenating the values following the spec. - keysMap := make(map[string][]string) - for itr.Next() { - kv := itr.Attribute() - key := model.EscapeName(string(kv.Key), model.NameEscapingScheme) - if _, ok := keysMap[key]; !ok { - keysMap[key] = []string{kv.Value.Emit()} - } else { - // if the sanitized key is a duplicate, append to the list of keys - keysMap[key] = append(keysMap[key], kv.Value.Emit()) - } - } - for key, vals := range keysMap { - keys = append(keys, key) - slices.Sort(vals) - values = append(values, strings.Join(vals, ";")) - } - } - return keys, values -} - -func createInfoMetric(name, description string, res *resource.Resource) (prometheus.Metric, error) { - keys, values := getAttrs(*res.Set()) - desc := prometheus.NewDesc(name, description, keys, nil) - return prometheus.NewConstMetric(desc, prometheus.GaugeValue, float64(1), values...) -} - -func createScopeInfoMetric(scope instrumentation.Scope) (prometheus.Metric, error) { - attrs := make([]attribute.KeyValue, 0, scope.Attributes.Len()+2) // resource attrs + scope name + scope version - attrs = append(attrs, scope.Attributes.ToSlice()...) - attrs = append(attrs, attribute.String(scopeNameLabel, scope.Name)) - attrs = append(attrs, attribute.String(scopeVersionLabel, scope.Version)) - - keys, values := getAttrs(attribute.NewSet(attrs...)) - desc := prometheus.NewDesc(scopeInfoMetricName, scopeInfoDescription, keys, nil) - return prometheus.NewConstMetric(desc, prometheus.GaugeValue, float64(1), values...) -} - -var unitSuffixes = 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": "_ratio", - "%": "_percent", -} - -// getName returns the sanitized name, prefixed with the namespace and suffixed with unit. -func (c *collector) getName(m metricdata.Metrics, typ *dto.MetricType) string { - name := m.Name - if model.NameValidationScheme != model.UTF8Validation { - // Only sanitize if prometheus does not support UTF-8. - name = model.EscapeName(name, model.NameEscapingScheme) - } - addCounterSuffix := !c.withoutCounterSuffixes && *typ == dto.MetricType_COUNTER - if addCounterSuffix { - // Remove the _total suffix here, as we will re-add the total suffix - // later, and it needs to come after the unit suffix. - name = strings.TrimSuffix(name, counterSuffix) - } - if c.namespace != "" { - name = c.namespace + name - } - if suffix, ok := unitSuffixes[m.Unit]; ok && !c.withoutUnits && !strings.HasSuffix(name, suffix) { - name += suffix - } - if addCounterSuffix { - name += counterSuffix - } - return name -} - -func (c *collector) metricType(m metricdata.Metrics) *dto.MetricType { - switch v := m.Data.(type) { - case metricdata.Histogram[int64], metricdata.Histogram[float64]: - return dto.MetricType_HISTOGRAM.Enum() - case metricdata.Sum[float64]: - if v.IsMonotonic { - return dto.MetricType_COUNTER.Enum() - } - return dto.MetricType_GAUGE.Enum() - case metricdata.Sum[int64]: - if v.IsMonotonic { - return dto.MetricType_COUNTER.Enum() - } - return dto.MetricType_GAUGE.Enum() - case metricdata.Gauge[int64], metricdata.Gauge[float64]: - return dto.MetricType_GAUGE.Enum() - } - return nil -} - -func (c *collector) createResourceAttributes(res *resource.Resource) { - c.mu.Lock() - defer c.mu.Unlock() - - resourceAttrs, _ := res.Set().Filter(c.resourceAttributesFilter) - resourceKeys, resourceValues := getAttrs(resourceAttrs) - c.resourceKeyVals = keyVals{keys: resourceKeys, vals: resourceValues} -} - -func (c *collector) scopeInfo(scope instrumentation.Scope) (prometheus.Metric, error) { - c.mu.Lock() - defer c.mu.Unlock() - - scopeInfo, ok := c.scopeInfos[scope] - if ok { - return scopeInfo, nil - } - - if _, ok := c.scopeInfosInvalid[scope]; ok { - return nil, errScopeInvalid - } - - scopeInfo, err := createScopeInfoMetric(scope) - if err != nil { - c.scopeInfosInvalid[scope] = struct{}{} - return nil, fmt.Errorf("cannot create scope info metric: %w", err) - } - - c.scopeInfos[scope] = scopeInfo - - return scopeInfo, nil -} - -func (c *collector) validateMetrics(name, description string, metricType *dto.MetricType) (drop bool, help string) { - c.mu.Lock() - defer c.mu.Unlock() - - emf, exist := c.metricFamilies[name] - - if !exist { - c.metricFamilies[name] = &dto.MetricFamily{ - Name: proto.String(name), - Help: proto.String(description), - Type: metricType, - } - return false, "" - } - - if emf.GetType() != *metricType { - global.Error( - errors.New("instrument type conflict"), - "Using existing type definition.", - "instrument", name, - "existing", emf.GetType(), - "dropped", *metricType, - ) - return true, "" - } - if emf.GetHelp() != description { - global.Info( - "Instrument description conflict, using existing", - "instrument", name, - "existing", emf.GetHelp(), - "dropped", description, - ) - return false, emf.GetHelp() - } - - return false, "" -} - -func addExemplars[N int64 | float64](m prometheus.Metric, exemplars []metricdata.Exemplar[N]) prometheus.Metric { - if len(exemplars) == 0 { - return m - } - promExemplars := make([]prometheus.Exemplar, len(exemplars)) - for i, exemplar := range exemplars { - labels := attributesToLabels(exemplar.FilteredAttributes) - // Overwrite any existing trace ID or span ID attributes - labels[traceIDExemplarKey] = hex.EncodeToString(exemplar.TraceID[:]) - labels[spanIDExemplarKey] = hex.EncodeToString(exemplar.SpanID[:]) - promExemplars[i] = prometheus.Exemplar{ - Value: float64(exemplar.Value), - Timestamp: exemplar.Time, - Labels: labels, - } - } - metricWithExemplar, err := prometheus.NewMetricWithExemplars(m, promExemplars...) - if err != nil { - // If there are errors creating the metric with exemplars, just warn - // and return the metric without exemplars. - otel.Handle(err) - return m - } - return metricWithExemplar -} - -func attributesToLabels(attrs []attribute.KeyValue) prometheus.Labels { - labels := make(map[string]string) - for _, attr := range attrs { - key := model.EscapeName(string(attr.Key), model.NameEscapingScheme) - labels[key] = attr.Value.Emit() - } - return labels -} |
