From 79067d5b69b061ec0c70e4e3f45e8f49e0dc81f8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 3 Sep 2026 18:53:02 +0000 Subject: [PATCH] chore: bump github.com/prometheus/common from 0.70.1 to 0.71.0 Bumps [github.com/prometheus/common](https://github.com/prometheus/common) from 0.70.1 to 0.71.0. - [Release notes](https://github.com/prometheus/common/releases) - [Changelog](https://github.com/prometheus/common/blob/main/CHANGELOG.md) - [Commits](https://github.com/prometheus/common/compare/v0.70.1...v0.71.0) --- updated-dependencies: - dependency-name: github.com/prometheus/common dependency-version: 0.71.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- go.mod | 2 +- go.sum | 4 +- .../prometheus/common/expfmt/decode.go | 19 +- .../prometheus/common/expfmt/encode.go | 152 +++++-- .../prometheus/common/expfmt/expfmt.go | 11 + .../common/expfmt/openmetrics_2_0_create.go | 425 ++++++++++++++++++ .../prometheus/common/model/signature.go | 10 +- .../prometheus/common/model/time.go | 28 ++ vendor/modules.txt | 2 +- 9 files changed, 589 insertions(+), 64 deletions(-) create mode 100644 vendor/github.com/prometheus/common/expfmt/openmetrics_2_0_create.go diff --git a/go.mod b/go.mod index d8f369f805..6f2eacad8a 100644 --- a/go.mod +++ b/go.mod @@ -28,7 +28,7 @@ require ( github.com/kylelemons/godebug v1.1.0 github.com/open-policy-agent/cert-controller v0.16.0 github.com/prometheus/client_golang v1.24.1 - github.com/prometheus/common v0.70.1 + github.com/prometheus/common v0.71.0 github.com/spf13/cobra v1.10.2 github.com/spyzhov/ajson v0.9.6 github.com/stretchr/testify v1.12.1 diff --git a/go.sum b/go.sum index e9dfcfc301..ad5454a4ea 100644 --- a/go.sum +++ b/go.sum @@ -300,8 +300,8 @@ github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/h github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= -github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY= -github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc= +github.com/prometheus/common v0.71.0 h1:9KDAKb7Mj3HEVKyFCK6Dc/HIwlBzZIN2l7/lrHl3KK8= +github.com/prometheus/common v0.71.0/go.mod h1:CLJ5H8TEsGX8bl31BdMkfhIZ+QmZ9tBPPotUxUbfcmk= github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI= github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= diff --git a/vendor/github.com/prometheus/common/expfmt/decode.go b/vendor/github.com/prometheus/common/expfmt/decode.go index 8f8dc65d38..0339d8c1d0 100644 --- a/vendor/github.com/prometheus/common/expfmt/decode.go +++ b/vendor/github.com/prometheus/common/expfmt/decode.go @@ -72,13 +72,15 @@ func ResponseFormat(h http.Header) Format { // NewDecoder returns a new decoder based on the given input format. Metric // names are validated based on the provided Format -- if the format requires -// escaping, raditional Prometheues validity checking is used. Otherwise, names +// escaping, traditional Prometheus validity checking is used. Otherwise, names // are checked for UTF-8 validity. Supported formats include delimited protobuf -// and Prometheus text format. For historical reasons, this decoder fallbacks -// to classic text decoding for any other format. This decoder does not fully -// support OpenMetrics although it may often succeed due to the similarities -// between the formats. This decoder may not support the latest features of -// Prometheus text format and is not intended for high-performance applications. +// and Prometheus text format. For historical reasons, this decoder falls back +// to classic text decoding for other legacy formats, but returns an error for +// unsupported formats such as OpenMetrics 2.0. This decoder does not fully +// support OpenMetrics although it may often succeed for OpenMetrics 1.0 due to +// the similarities between the formats. This decoder may not support the latest +// features of Prometheus text format and is not intended for high-performance +// applications. // See: https://github.com/prometheus/common/issues/812 func NewDecoder(r io.Reader, format Format) Decoder { scheme := model.LegacyValidation @@ -90,6 +92,11 @@ func NewDecoder(r io.Reader, format Format) Decoder { return &protoDecoder{r: bufio.NewReader(r), s: scheme} case TypeProtoText, TypeProtoCompact: return &errDecoder{err: fmt.Errorf("format %s not supported for decoding", format)} + case TypeOpenMetrics: + _, params, err := mime.ParseMediaType(string(format)) + if err == nil && params["version"] == OpenMetricsVersion_2_0_0 { + return &errDecoder{err: fmt.Errorf("format %s not supported for decoding", format)} + } } return &textDecoder{r: r, s: scheme} } diff --git a/vendor/github.com/prometheus/common/expfmt/encode.go b/vendor/github.com/prometheus/common/expfmt/encode.go index 73c24dfbc9..6945356ca5 100644 --- a/vendor/github.com/prometheus/common/expfmt/encode.go +++ b/vendor/github.com/prometheus/common/expfmt/encode.go @@ -16,6 +16,7 @@ package expfmt import ( "fmt" "io" + "mime" "net/http" "github.com/munnerz/goautoneg" @@ -26,6 +27,24 @@ import ( "github.com/prometheus/common/model" ) +var formatToAccept = map[Format]goautoneg.Accept{} + +func init() { + for _, f := range []Format{ + FmtText, + FmtProtoDelim, + FmtProtoText, + FmtProtoCompact, + FmtOpenMetrics_1_0_0, + fmtOpenMetrics_2_0_0, + FmtOpenMetrics_0_0_1, + } { + if parsed := goautoneg.ParseAccept(string(f)); len(parsed) > 0 { + formatToAccept[f] = parsed[0] + } + } +} + // Encoder types encode metric families into an underlying wire protocol. type Encoder interface { Encode(*dto.MetricFamily) error @@ -57,11 +76,30 @@ func (ec encoderCloser) Close() error { // Negotiate returns the Content-Type based on the given Accept header. If no // appropriate accepted type is found, FmtText is returned (which is the -// Prometheus text format). This function will never negotiate FmtOpenMetrics, -// as the support is still experimental. To include the option to negotiate -// FmtOpenMetrics, use NegotiateIncludingOpenMetrics. +// Prometheus text format). +// +// Deprecated: Use NegotiateAccept(h, FmtProtoDelim, FmtProtoText, FmtProtoCompact, FmtText) +// or specify only the formats supported by your server. func Negotiate(h http.Header) Format { - escapingScheme := Format(fmt.Sprintf("; escaping=%s", Format(model.NameEscapingScheme.String()))) + return NegotiateAccept(h, FmtProtoDelim, FmtProtoText, FmtProtoCompact, FmtText) +} + +// NegotiateIncludingOpenMetrics works like Negotiate but includes +// FmtOpenMetrics as an option for the result. +// +// Deprecated: Use NegotiateAccept(h, FmtOpenMetrics_1_0_0, FmtOpenMetrics_0_0_1, FmtProtoDelim, FmtProtoText, FmtProtoCompact, FmtText) +// or specify only the formats supported by your server. +func NegotiateIncludingOpenMetrics(h http.Header) Format { + return NegotiateAccept(h, FmtOpenMetrics_1_0_0, FmtOpenMetrics_0_0_1, FmtProtoDelim, FmtProtoText, FmtProtoCompact, FmtText) +} + +// NegotiateAccept returns the Content-Type based on the given Accept header +// and the list of accepted Formats provided by the caller, in order of preference. +// If no accepted format matches the Accept header, it falls back to the text +// format if present in the accepted list, or the first accepted format (or FmtText +// if accepted is empty). +func NegotiateAccept(h http.Header, accepted ...Format) Format { + escapingScheme := Format("; escaping=" + model.NameEscapingScheme.String()) for _, ac := range goautoneg.ParseAccept(h.Get(hdrAccept)) { if escapeParam := ac.Params[model.EscapingKey]; escapeParam != "" { switch Format(escapeParam) { @@ -71,63 +109,66 @@ func Negotiate(h http.Header) Format { // If the escaping parameter is unknown, ignore it. } } - ver := ac.Params["version"] - if ac.Type+"/"+ac.SubType == ProtoType && ac.Params["proto"] == ProtoProtocol { - switch ac.Params["encoding"] { - case "delimited": - return FmtProtoDelim + escapingScheme - case "text": - return FmtProtoText + escapingScheme - case "compact-text": - return FmtProtoCompact + escapingScheme + + for _, f := range accepted { + if matchFormat(ac, f) { + return f + escapingScheme } } - if ac.Type == "text" && ac.SubType == "plain" && (ver == TextVersion || ver == "") { - return FmtText + escapingScheme + } + for _, f := range accepted { + if f.FormatType() == TypeTextPlain { + return f + escapingScheme } } + if len(accepted) > 0 { + return accepted[0] + escapingScheme + } return FmtText + escapingScheme } -// NegotiateIncludingOpenMetrics works like Negotiate but includes -// FmtOpenMetrics as an option for the result. Note that this function is -// temporary and will disappear once FmtOpenMetrics is fully supported and as -// such may be negotiated by the normal Negotiate function. -func NegotiateIncludingOpenMetrics(h http.Header) Format { - escapingScheme := Format(fmt.Sprintf("; escaping=%s", Format(model.NameEscapingScheme.String()))) - for _, ac := range goautoneg.ParseAccept(h.Get(hdrAccept)) { - if escapeParam := ac.Params[model.EscapingKey]; escapeParam != "" { - switch Format(escapeParam) { - case model.AllowUTF8, model.EscapeUnderscores, model.EscapeDots, model.EscapeValues: - escapingScheme = Format("; escaping=" + escapeParam) - default: - // If the escaping parameter is unknown, ignore it. - } +// matchFormat checks if a parsed accept clause matches a given Format. +func matchFormat(ac goautoneg.Accept, f Format) bool { + target, ok := formatToAccept[f] + if !ok { + parsed := goautoneg.ParseAccept(string(f)) + if len(parsed) == 0 { + return false } - ver := ac.Params["version"] - if ac.Type+"/"+ac.SubType == ProtoType && ac.Params["proto"] == ProtoProtocol { - switch ac.Params["encoding"] { - case "delimited": - return FmtProtoDelim + escapingScheme - case "text": - return FmtProtoText + escapingScheme - case "compact-text": - return FmtProtoCompact + escapingScheme - } + target = parsed[0] + } + + if ac.Type != "*" && ac.Type != target.Type { + return false + } + if ac.SubType != "*" && ac.SubType != target.SubType { + return false + } + + // Default OpenMetrics version to OpenMetricsVersion_0_0_1. + acVersion := ac.Params["version"] + if acVersion == "" && ac.Type+"/"+ac.SubType == OpenMetricsType { + acVersion = OpenMetricsVersion_0_0_1 + } + if acVersion == "" && ac.Type == "text" && ac.SubType == "plain" { + acVersion = TextVersion + } + + // General param matching. + for k, v := range target.Params { + if k == "charset" { + continue } - if ac.Type == "text" && ac.SubType == "plain" && (ver == TextVersion || ver == "") { - return FmtText + escapingScheme + acVal := ac.Params[k] + if k == "version" { + acVal = acVersion } - if ac.Type+"/"+ac.SubType == OpenMetricsType && (ver == OpenMetricsVersion_0_0_1 || ver == OpenMetricsVersion_1_0_0 || ver == "") { - switch ver { - case OpenMetricsVersion_1_0_0: - return FmtOpenMetrics_1_0_0 + escapingScheme - default: - return FmtOpenMetrics_0_0_1 + escapingScheme - } + if acVal != v { + return false } } - return FmtText + escapingScheme + + return true } // NewEncoder returns a new encoder based on content type negotiation. All @@ -181,6 +222,19 @@ func NewEncoder(w io.Writer, format Format, options ...EncoderOption) Encoder { close: func() error { return nil }, } case TypeOpenMetrics: + _, params, err := mime.ParseMediaType(string(format)) + if err == nil && params["version"] == OpenMetricsVersion_2_0_0 { + return encoderCloser{ + encode: func(v *dto.MetricFamily) error { + _, err := MetricFamilyToOpenMetrics20(w, model.EscapeMetricFamily(v, escapingScheme), options...) + return err + }, + close: func() error { + _, err := FinalizeOpenMetrics(w) + return err + }, + } + } return encoderCloser{ encode: func(v *dto.MetricFamily) error { _, err := MetricFamilyToOpenMetrics(w, model.EscapeMetricFamily(v, escapingScheme), options...) diff --git a/vendor/github.com/prometheus/common/expfmt/expfmt.go b/vendor/github.com/prometheus/common/expfmt/expfmt.go index 10bf35708c..40035f2013 100644 --- a/vendor/github.com/prometheus/common/expfmt/expfmt.go +++ b/vendor/github.com/prometheus/common/expfmt/expfmt.go @@ -42,6 +42,8 @@ const ( OpenMetricsVersion_0_0_1 = "0.0.1" //nolint:revive // Allow for underscores. OpenMetricsVersion_1_0_0 = "1.0.0" + //nolint:revive // Allow for underscores. + OpenMetricsVersion_2_0_0 = "2.0.0" // The Content-Type values for the different wire protocols. Do not do direct // comparisons to these constants, instead use the comparison functions. @@ -59,6 +61,8 @@ const ( // Deprecated: Use expfmt.NewFormat(expfmt.TypeOpenMetrics) instead. //nolint:revive // Allow for underscores. FmtOpenMetrics_1_0_0 Format = OpenMetricsType + `; version=` + OpenMetricsVersion_1_0_0 + `; charset=utf-8` + //nolint:revive // Allow for underscores. + fmtOpenMetrics_2_0_0 Format = OpenMetricsType + `; version=` + OpenMetricsVersion_2_0_0 + `; charset=utf-8` // Deprecated: Use expfmt.NewFormat(expfmt.TypeOpenMetrics) instead. //nolint:revive // Allow for underscores. FmtOpenMetrics_0_0_1 Format = OpenMetricsType + `; version=` + OpenMetricsVersion_0_0_1 + `; charset=utf-8` @@ -107,6 +111,9 @@ func NewFormat(t FormatType) Format { // NewOpenMetricsFormat generates a new OpenMetrics format matching the // specified version number. +// +// Note: OpenMetrics version 2.0.0 is experimental and encode-only (currently +// supporting counter, gauge, and untyped metric types). func NewOpenMetricsFormat(version string) (Format, error) { if version == OpenMetricsVersion_0_0_1 { return FmtOpenMetrics_0_0_1, nil @@ -114,6 +121,10 @@ func NewOpenMetricsFormat(version string) (Format, error) { if version == OpenMetricsVersion_1_0_0 { return FmtOpenMetrics_1_0_0, nil } + if version == OpenMetricsVersion_2_0_0 { + // OpenMetrics 2.0.0 is experimental and encode-only (counter/gauge/untyped). + return fmtOpenMetrics_2_0_0, nil + } return FmtUnknown, errors.New("unknown open metrics version string") } diff --git a/vendor/github.com/prometheus/common/expfmt/openmetrics_2_0_create.go b/vendor/github.com/prometheus/common/expfmt/openmetrics_2_0_create.go new file mode 100644 index 0000000000..8ca9b6be76 --- /dev/null +++ b/vendor/github.com/prometheus/common/expfmt/openmetrics_2_0_create.go @@ -0,0 +1,425 @@ +// Copyright 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 expfmt + +import ( + "bufio" + "errors" + "fmt" + "io" + "math" + "strconv" + "strings" + + dto "github.com/prometheus/client_model/go" + "google.golang.org/protobuf/types/known/timestamppb" +) + +// MetricFamilyToOpenMetrics20 converts a MetricFamily proto message into the +// OpenMetrics text format version 2.0.0 and writes the resulting lines to 'out'. +// It returns the number of bytes written and any error encountered. +// +// NOTE: This method targets OpenMetrics 2.0.0 (currently aligned with 2.0-rc.0) which is experimental and +// encode-only (currently supporting counter, gauge, and untyped metric types). +// Breaking changes might happen in the future. This implementation is still a +// work-in-progress, and does not yet support all features of the format. +// EncoderOptions are accepted for signature compatibility with +// MetricFamilyToOpenMetrics and are currently ignored. +func MetricFamilyToOpenMetrics20(out io.Writer, in *dto.MetricFamily, options ...EncoderOption) (written int, err error) { + // Options are accepted for signature compatibility and ignored. + _ = options + name := in.GetName() + if name == "" { + return 0, fmt.Errorf("MetricFamily has no name: %s", in) + } + if containsRawNewline(name) { + return 0, fmt.Errorf("MetricFamily name %q contains raw newlines", name) + } + if in.Unit != nil && containsRawNewline(*in.Unit) { + return 0, fmt.Errorf("MetricFamily unit %q contains raw newlines", *in.Unit) + } + + // Try the interface upgrade. If it doesn't work, we'll use a + // bufio.Writer from the sync.Pool. + w, ok := out.(enhancedWriter) + if !ok { + b := bufPool.Get().(*bufio.Writer) + b.Reset(out) + w = b + defer func() { + bErr := b.Flush() + if err == nil { + err = bErr + } + bufPool.Put(b) + }() + } + + var ( + n int + metricType = in.GetType() + ) + + // Comments, first HELP, then TYPE. + if in.Help != nil { + n, err = w.WriteString("# HELP ") + written += n + if err != nil { + return written, err + } + n, err = writeName(w, name) + written += n + if err != nil { + return written, err + } + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + n, err = writeEscapedString(w, *in.Help, true) + written += n + if err != nil { + return written, err + } + err = w.WriteByte('\n') + written++ + if err != nil { + return written, err + } + } + n, err = w.WriteString("# TYPE ") + written += n + if err != nil { + return written, err + } + n, err = writeName(w, name) + written += n + if err != nil { + return written, err + } + switch metricType { + case dto.MetricType_COUNTER: + n, err = w.WriteString(" counter\n") + case dto.MetricType_GAUGE: + n, err = w.WriteString(" gauge\n") + case dto.MetricType_SUMMARY: + n, err = w.WriteString(" summary\n") + case dto.MetricType_UNTYPED: + n, err = w.WriteString(" unknown\n") + case dto.MetricType_HISTOGRAM: + n, err = w.WriteString(" histogram\n") + case dto.MetricType_GAUGE_HISTOGRAM: + n, err = w.WriteString(" gaugehistogram\n") + default: + // TODO: Support Info and StateSet once they are supported in the + // Prometheus protobuf format. + return written, fmt.Errorf("unknown metric type %s", metricType.String()) + } + written += n + if err != nil { + return written, err + } + if in.Unit != nil { + n, err = w.WriteString("# UNIT ") + written += n + if err != nil { + return written, err + } + n, err = writeName(w, name) + written += n + if err != nil { + return written, err + } + + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + n, err = writeEscapedString(w, *in.Unit, true) + written += n + if err != nil { + return written, err + } + err = w.WriteByte('\n') + written++ + if err != nil { + return written, err + } + } + + // Finally the samples, one line for each. + for _, metric := range in.Metric { + if metric == nil { + return written, fmt.Errorf("expected non-nil metric in MetricFamily %s", name) + } + switch metricType { + case dto.MetricType_COUNTER: + if metric.Counter == nil { + return written, fmt.Errorf("expected counter in metric %s %s", name, metric) + } + val := metric.Counter.GetValue() + if math.IsNaN(val) { + return written, fmt.Errorf("counter value cannot be NaN in metric %s", name) + } + if val < 0 { + return written, fmt.Errorf("counter value cannot be negative (%g) in metric %s", val, name) + } + n, err = writeOpenMetrics20Sample(w, name, metric, val, 0, false, metric.Counter.CreatedTimestamp, metric.Counter.Exemplar) + case dto.MetricType_GAUGE: + if metric.Gauge == nil { + return written, fmt.Errorf("expected gauge in metric %s %s", name, metric) + } + n, err = writeOpenMetrics20Sample(w, name, metric, metric.Gauge.GetValue(), 0, false, nil, nil) + case dto.MetricType_UNTYPED: + if metric.Untyped == nil { + return written, fmt.Errorf("expected untyped in metric %s %s", name, metric) + } + n, err = writeOpenMetrics20Sample(w, name, metric, metric.Untyped.GetValue(), 0, false, nil, nil) + case dto.MetricType_SUMMARY: + if metric.Summary == nil { + return written, fmt.Errorf("expected summary in metric %s %s", name, metric) + } + n, err = writeCompositeSummary(w, name, metric) + case dto.MetricType_HISTOGRAM, dto.MetricType_GAUGE_HISTOGRAM: + if metric.Histogram == nil { + return written, fmt.Errorf("expected histogram in metric %s %s", name, metric) + } + n, err = writeCompositeHistogram(w, name, metric, metricType == dto.MetricType_GAUGE_HISTOGRAM) + default: + return written, fmt.Errorf("unexpected type in metric %s %s", name, metric) + } + written += n + if err != nil { + return written, err + } + } + return written, nil +} + +// writeOpenMetrics20Sample writes a single sample for simple types (Counter, Gauge, Untyped). +func writeOpenMetrics20Sample(w enhancedWriter, name string, metric *dto.Metric, floatValue float64, intValue uint64, useIntValue bool, startTimestamp *timestamppb.Timestamp, exemplar *dto.Exemplar) (int, error) { + if err := validateLabels20(metric.Label); err != nil { + return 0, err + } + written := 0 + n, err := writeOpenMetricsNameAndLabelPairs(w, name, metric.Label, "", 0) + written += n + if err != nil { + return written, err + } + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + + if useIntValue { + n, err = writeUint(w, intValue) + } else { + n, err = writeOpenMetricsFloat(w, floatValue) + } + written += n + if err != nil { + return written, err + } + + if metric.TimestampMs != nil { + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + n, err = writeOpenMetrics20Timestamp(w, float64(*metric.TimestampMs)/1000) + written += n + if err != nil { + return written, err + } + } + + // Start Timestamp + if startTimestamp != nil { + if err := startTimestamp.CheckValid(); err != nil { + return written, fmt.Errorf("invalid created timestamp in metric %s: %w", name, err) + } + n, err = w.WriteString(" st@") + written += n + if err != nil { + return written, err + } + n, err = writeProtoTimestamp(w, startTimestamp) + written += n + if err != nil { + return written, err + } + } + + if exemplar != nil { + n, err = writeExemplar20(w, exemplar) + written += n + if err != nil { + return written, err + } + } + + err = w.WriteByte('\n') + written++ + if err != nil { + return written, err + } + return written, nil +} + +// writeExemplar20 writes the provided exemplar in OpenMetrics 2.0 format to w. +// In OpenMetrics 2.0, invalid exemplars or exemplars without a timestamp are dropped. +func writeExemplar20(w enhancedWriter, e *dto.Exemplar) (int, error) { + if e == nil { + return 0, nil + } + // In OpenMetrics 2.0, invalid exemplars are dropped rather than failing the entire exposition. + if err := validateExemplar20(e); err != nil { + return 0, nil + } + written := 0 + n, err := w.WriteString(" # ") + written += n + if err != nil { + return written, err + } + if len(e.Label) == 0 { + n, err = w.WriteString("{}") + } else { + n, err = writeOpenMetricsNameAndLabelPairs(w, "", e.Label, "", 0) + } + written += n + if err != nil { + return written, err + } + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + n, err = writeOpenMetricsFloat(w, e.GetValue()) + written += n + if err != nil { + return written, err + } + err = w.WriteByte(' ') + written++ + if err != nil { + return written, err + } + ts := e.Timestamp + n, err = writeProtoTimestamp(w, ts) + written += n + if err != nil { + return written, err + } + return written, nil +} + +// writeOpenMetrics20Timestamp writes a float64 as a timestamp without scientific notation. +func writeOpenMetrics20Timestamp(w enhancedWriter, f float64) (int, error) { + bp := numBufPool.Get().(*[]byte) + *bp = strconv.AppendFloat((*bp)[:0], f, 'f', -1, 64) + written, err := w.Write(*bp) + numBufPool.Put(bp) + return written, err +} + +// Stubs for Summary and Histogram + +func writeCompositeSummary(w enhancedWriter, name string, metric *dto.Metric) (int, error) { + _ = w + _ = name + _ = metric + return 0, errors.New("summary not implemented yet") +} + +func writeCompositeHistogram(w enhancedWriter, name string, metric *dto.Metric, isGauge bool) (int, error) { + _ = w + _ = name + _ = metric + _ = isGauge + return 0, errors.New("histogram not implemented yet") +} + +func validateLabels20(labels []*dto.LabelPair) error { + for _, lp := range labels { + if lp == nil { + return errors.New("expected non-nil label pair") + } + lname := lp.GetName() + if lname == "" { + return errors.New("label name cannot be empty") + } + if containsRawNewline(lname) { + return fmt.Errorf("label name %q contains raw newlines", lname) + } + } + return nil +} + +func containsRawNewline(s string) bool { + return strings.IndexByte(s, '\n') >= 0 || strings.IndexByte(s, '\r') >= 0 +} + +func validateExemplar20(e *dto.Exemplar) error { + if e.Timestamp == nil { + return errors.New("exemplar timestamp is required") + } + if err := e.Timestamp.CheckValid(); err != nil { + return err + } + return validateLabels20(e.Label) +} + +func writeProtoTimestamp(w enhancedWriter, ts *timestamppb.Timestamp) (int, error) { + if err := ts.CheckValid(); err != nil { + return 0, err + } + n, err := writeInt(w, ts.Seconds) + if err != nil { + return n, err + } + if ts.Nanos == 0 { + return n, nil + } + err = w.WriteByte('.') + written := n + 1 + if err != nil { + return written, err + } + bp := numBufPool.Get().(*[]byte) + *bp = strconv.AppendInt((*bp)[:0], int64(ts.Nanos), 10) + pad := 9 - len(*bp) + for range pad { + err = w.WriteByte('0') + written++ + if err != nil { + numBufPool.Put(bp) + return written, err + } + } + val := *bp + for len(val) > 0 && val[len(val)-1] == '0' { + val = val[:len(val)-1] + } + n2, err := w.Write(val) + written += n2 + numBufPool.Put(bp) + return written, err +} diff --git a/vendor/github.com/prometheus/common/model/signature.go b/vendor/github.com/prometheus/common/model/signature.go index dc8a0026c4..b723e3bb2d 100644 --- a/vendor/github.com/prometheus/common/model/signature.go +++ b/vendor/github.com/prometheus/common/model/signature.go @@ -14,7 +14,7 @@ package model import ( - "sort" + "slices" ) // SeparatorByte is a byte that cannot occur in valid UTF-8 sequences and is @@ -37,7 +37,7 @@ func LabelsToSignature(labels map[string]string) uint64 { for labelName := range labels { labelNames = append(labelNames, labelName) } - sort.Strings(labelNames) + slices.Sort(labelNames) sum := hashNew() for _, labelName := range labelNames { @@ -60,7 +60,7 @@ func labelSetToFingerprint(ls LabelSet) Fingerprint { for labelName := range ls { labelNames = append(labelNames, labelName) } - sort.Sort(labelNames) + slices.Sort(labelNames) sum := hashNew() for _, labelName := range labelNames { @@ -100,7 +100,7 @@ func SignatureForLabels(m Metric, labels ...LabelName) uint64 { return emptyLabelSignature } - sort.Sort(LabelNames(labels)) + slices.Sort(labels) sum := hashNew() for _, label := range labels { @@ -129,7 +129,7 @@ func SignatureWithoutLabels(m Metric, labels map[LabelName]struct{}) uint64 { if len(labelNames) == 0 { return emptyLabelSignature } - sort.Sort(labelNames) + slices.Sort(labelNames) sum := hashNew() for _, labelName := range labelNames { diff --git a/vendor/github.com/prometheus/common/model/time.go b/vendor/github.com/prometheus/common/model/time.go index 0854753f4a..9860717422 100644 --- a/vendor/github.com/prometheus/common/model/time.go +++ b/vendor/github.com/prometheus/common/model/time.go @@ -164,6 +164,34 @@ func (t *Time) UnmarshalJSON(b []byte) error { // This type should not propagate beyond the scope of input/output processing. type Duration time.Duration +// Common durations. Day and Week are included because ParseDuration supports +// those units (unlike the standard time package). +// +// To count the number of units in a Duration, divide: +// +// second := model.Second +// fmt.Print(int64(second/model.Millisecond)) // prints 1000 +// +// To convert an integer number of units to a Duration, multiply: +// +// seconds := 10 +// fmt.Print(model.Duration(seconds)*model.Second) // prints 10s +const ( + Nanosecond Duration = 1 + Microsecond = 1000 * Nanosecond + Millisecond = 1000 * Microsecond + Second = 1000 * Millisecond + Minute = 60 * Second + Hour = 60 * Minute + Day = 24 * Hour + Week = 7 * Day +) + +// Milliseconds returns the duration as an integer millisecond count. +// Prometheus stores timestamps in milliseconds; time.Duration already +// covers the other units. +func (d Duration) Milliseconds() int64 { return time.Duration(d).Milliseconds() } + // Set implements pflag/flag.Value. func (d *Duration) Set(s string) error { var err error diff --git a/vendor/modules.txt b/vendor/modules.txt index 55ee5328f3..1f9f815ccf 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -451,7 +451,7 @@ github.com/prometheus/client_golang/prometheus/promhttp/internal # github.com/prometheus/client_model v0.6.2 ## explicit; go 1.22.0 github.com/prometheus/client_model/go -# github.com/prometheus/common v0.70.1 +# github.com/prometheus/common v0.71.0 ## explicit; go 1.25.0 github.com/prometheus/common/expfmt github.com/prometheus/common/model