MSP-8974 up deps

This commit is contained in:
chashintv committed 2026-11-20 10:42:39 +03:00
1 parent 0abaaf740f
commit a0aafd93b9
602 files changed
+47724 -13295

No files matched your search

+86 -7
View File
@@ -61,10 +61,30 @@ func ResponseFormat(h http.Header) Format {
return FmtProtoDelim
case textType:
if params["version"] == TextVersion_1_0_0 {
if _, ok := params[model.EscapingKey]; ok {
return FmtText_1_0_0.WithEscapingScheme(Format(ct).ToEscapingScheme())
}
return FmtText_1_0_0
}
if v, ok := params["version"]; ok && v != TextVersion {
return FmtUnknown
}
return FmtText
case OpenMetricsType:
switch params["version"] {
case "", OpenMetricsVersion_0_0_1:
return FmtOpenMetrics_0_0_1
case OpenMetricsVersion_1_0_0:
return FmtOpenMetrics_1_0_0
case OpenMetricsVersion_2_0_0_rc:
return FmtOpenMetrics_2_0_0_rc
case OpenMetricsVersion_2_0_0:
return FmtOpenMetrics_2_0_0
default:
return FmtUnknown
}
}
return FmtUnknown
@@ -72,13 +92,13 @@ 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
// 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.
// escaping, traditional Prometheus validity checking is used. Otherwise, names
// are checked for UTF-8 validity. Supported formats include delimited protobuf,
// Prometheus text format, and OpenMetrics 0.0.1 / 1.0.0 / 2.0.0-rc / 2.0.0. For historical
// reasons, this decoder falls back to classic text decoding for other legacy
// formats, and returns an error for unsupported formats such as text protobuf.
// 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 +110,26 @@ 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 {
return &errDecoder{err: fmt.Errorf("format %s not supported for decoding", format)}
}
switch params["version"] {
case "", OpenMetricsVersion_0_0_1, OpenMetricsVersion_1_0_0:
return &openMetricsDecoder{p: newOpenMetricsParser(r, scheme)}
case OpenMetricsVersion_2_0_0_rc, OpenMetricsVersion_2_0_0:
// format.ToEscapingScheme() defaults to UnderscoreEscaping when no escaping
// parameter is set, whereas OpenMetrics 2.0 supports UTF-8 names by default
// unless a non-UTF-8 escaping scheme is explicitly requested.
om2Scheme := model.UTF8Validation
if _, hasEscaping := params[model.EscapingKey]; hasEscaping && format.ToEscapingScheme() != model.NoEscaping {
om2Scheme = model.LegacyValidation
}
return &openMetrics20Decoder{p: newOpenMetrics20Parser(r, om2Scheme)}
default:
return &errDecoder{err: fmt.Errorf("format %s not supported for decoding", format)}
}
}
return &textDecoder{r: r, s: scheme}
}
@@ -139,6 +179,45 @@ func (d *errDecoder) Decode(*dto.MetricFamily) error {
return d.err
}
// openMetricsDecoder implements the Decoder interface for the OpenMetrics 1.0 protocol.
type openMetricsDecoder struct {
p *openMetricsParser
err error
}
// Decode implements the Decoder interface.
func (d *openMetricsDecoder) Decode(v *dto.MetricFamily) error {
if d.err != nil {
return d.err
}
if err := d.p.next(v); err != nil {
d.err = err
return err
}
return nil
}
// openMetrics20Decoder implements the Decoder interface for the OpenMetrics 2.0 protocol.
// Like openMetricsDecoder, it uses goabnf.ParseForest per line without a line-length
// cap (which has superlinear parse time in line length) and is intended for
// reference/conformance decoding rather than high-performance or untrusted inputs.
type openMetrics20Decoder struct {
p *openMetrics20Parser
err error
}
// Decode implements the Decoder interface.
func (d *openMetrics20Decoder) Decode(v *dto.MetricFamily) error {
if d.err != nil {
return d.err
}
if err := d.p.next(v); err != nil {
d.err = err
return err
}
return nil
}
// textDecoder implements the Decoder interface for the text protocol.
type textDecoder struct {
r io.Reader
+155 -57
View File
@@ -16,7 +16,9 @@ package expfmt
import (
"fmt"
"io"
"mime"
"net/http"
"slices"
"github.com/munnerz/goautoneg"
dto "github.com/prometheus/client_model/go"
@@ -26,6 +28,60 @@ import (
"github.com/prometheus/common/model"
)
var formatToAccept = map[Format]goautoneg.Accept{}
func init() {
for _, f := range []Format{
FmtText,
FmtText_1_0_0,
FmtProtoDelim,
FmtProtoText,
FmtProtoCompact,
FmtOpenMetrics_1_0_0,
FmtOpenMetrics_2_0_0_rc,
FmtOpenMetrics_2_0_0,
FmtOpenMetrics_0_0_1,
} {
if parsed := goautoneg.ParseAccept(string(f)); len(parsed) > 0 {
formatToAccept[f] = parsed[0]
}
}
}
var (
defaultAcceptedFormats = []Format{
FmtProtoDelim,
FmtProtoText,
FmtProtoCompact,
FmtText,
FmtText_1_0_0,
}
defaultOpenMetricsAcceptedFormats = []Format{
FmtOpenMetrics_1_0_0,
FmtOpenMetrics_0_0_1,
FmtProtoDelim,
FmtProtoText,
FmtProtoCompact,
FmtText,
FmtText_1_0_0,
}
)
// DefaultAcceptedFormats returns a copy of standard accepted formats for Negotiate,
// ordered by preference (delimited protobuf, protobuf text, compact protobuf text,
// and Prometheus text formats). Version 0.0.4 remains the fallback when no
// supported version is requested.
func DefaultAcceptedFormats() []Format {
return slices.Clone(defaultAcceptedFormats)
}
// DefaultOpenMetricsAcceptedFormats returns a copy of standard accepted formats including
// stable OpenMetrics formats, ordered by preference.
func DefaultOpenMetricsAcceptedFormats() []Format {
return slices.Clone(defaultOpenMetricsAcceptedFormats)
}
// Encoder types encode metric families into an underlying wire protocol.
type Encoder interface {
Encode(*dto.MetricFamily) error
@@ -57,77 +113,106 @@ 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, DefaultAcceptedFormats()...)
// 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, defaultAcceptedFormats...)
}
// NegotiateIncludingOpenMetrics works like Negotiate but includes all stable
// FmtOpenMetrics formats as an option for the result.
//
// Deprecated: Use NegotiateAccept(h, DefaultOpenMetricsAcceptedFormats()...)
// or specify only the formats supported by your server.
func NegotiateIncludingOpenMetrics(h http.Header) Format {
return NegotiateAccept(h, defaultOpenMetricsAcceptedFormats...)
}
// 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).
// The escaping scheme is taken from the matching Accept clause. Without one,
// OpenMetrics 2.0 gets allow-utf-8 and all other formats model.NameEscapingScheme.
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) {
case model.AllowUTF8, model.EscapeUnderscores, model.EscapeDots, model.EscapeValues:
escapingScheme = Format("; escaping=" + escapeParam)
default:
// If the escaping parameter is unknown, ignore it.
for _, f := range accepted {
if matchFormat(ac, f) {
return f + escapingFor(ac, f)
}
}
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
}
}
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.
}
// escapingFor returns the escaping term for the Accept clause that matched f.
func escapingFor(ac goautoneg.Accept, f Format) Format {
switch p := ac.Params[model.EscapingKey]; p {
case model.AllowUTF8, model.EscapeUnderscores, model.EscapeDots, model.EscapeValues:
// An explicit request always wins, also for OpenMetrics 2.0.
return Format("; escaping=" + p)
}
if f.FormatType() == TypeOpenMetrics && isOpenMetrics20Version(f.Version()) {
// OpenMetrics 2.0 is UTF-8 native, so asking for it implies UTF-8 name support.
return Format("; escaping=" + model.AllowUTF8)
}
return Format("; escaping=" + model.NameEscapingScheme.String())
}
// 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 +266,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 && isOpenMetrics20Version(params["version"]) {
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...)
+87 -56
View File
@@ -16,50 +16,56 @@ package expfmt
import (
"errors"
"mime"
"strings"
"github.com/prometheus/common/model"
)
// Format specifies the HTTP content type of the different wire protocols.
type Format string
// Constants to assemble the Content-Type values for the different wire
// protocols. The Content-Type strings here are all for the legacy exposition
// formats, where valid characters for metric names and label names are limited.
// Support for arbitrary UTF-8 characters in those names is already partially
// implemented in this module (see model.ValidationScheme), but to actually use
// it on the wire, new content-type strings will have to be agreed upon and
// added here.
// protocols.
const (
TextVersion = "0.0.4"
ProtoType = `application/vnd.google.protobuf`
ProtoProtocol = `io.prometheus.client.MetricFamily`
// Deprecated: Use expfmt.NewFormat(expfmt.TypeProtoCompact) instead.
ProtoFmt = ProtoType + "; proto=" + ProtoProtocol + ";"
TextVersion = "0.0.4"
//nolint:revive // Allow for underscores.
TextVersion_1_0_0 = "1.0.0"
ProtoType = `application/vnd.google.protobuf`
ProtoProtocol = `io.prometheus.client.MetricFamily`
ProtoFmt = ProtoType + "; proto=" + ProtoProtocol + ";"
OpenMetricsType = `application/openmetrics-text`
//nolint:revive // Allow for underscores.
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_rc = "2.0.0-rc"
//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.
//
// Deprecated: Use expfmt.NewFormat(expfmt.TypeUnknown) instead.
// Format specifies the HTTP content type of the different wire protocols.
// The Content-Type values for the different wire protocols represent
// baseline Content-Types used for HTTP headers and content negotiation.
//
// Because Content-Types on the wire may include dynamic parameters
// (such as "; escaping=...") or whitespace variations, avoid comparing Format
// values using direct equality (==).
type Format string
const (
FmtUnknown Format = `<unknown>`
// Deprecated: Use expfmt.NewFormat(expfmt.TypeTextPlain) instead.
FmtText Format = `text/plain; version=` + TextVersion + `; charset=utf-8`
// Deprecated: Use expfmt.NewFormat(expfmt.TypeProtoDelim) instead.
FmtProtoDelim Format = ProtoFmt + ` encoding=delimited`
// Deprecated: Use expfmt.NewFormat(expfmt.TypeProtoText) instead.
FmtProtoText Format = ProtoFmt + ` encoding=text`
// Deprecated: Use expfmt.NewFormat(expfmt.TypeProtoCompact) instead.
FmtText Format = `text/plain; version=` + TextVersion + `; charset=utf-8`
//nolint:revive // Allow for underscores.
FmtText_1_0_0 Format = `text/plain; version=` + TextVersion_1_0_0 + `; charset=utf-8`
FmtProtoDelim Format = ProtoFmt + ` encoding=delimited`
FmtProtoText Format = ProtoFmt + ` encoding=text`
FmtProtoCompact Format = ProtoFmt + ` encoding=compact-text`
// Deprecated: Use expfmt.NewFormat(expfmt.TypeOpenMetrics) instead.
//nolint:revive // Allow for underscores.
FmtOpenMetrics_2_0_0 Format = OpenMetricsType + `; version=` + OpenMetricsVersion_2_0_0 + `; charset=utf-8`
//nolint:revive // Allow for underscores.
FmtOpenMetrics_2_0_0_rc Format = OpenMetricsType + `; version=` + OpenMetricsVersion_2_0_0_rc + `; charset=utf-8`
//nolint:revive // Allow for underscores.
FmtOpenMetrics_1_0_0 Format = OpenMetricsType + `; version=` + OpenMetricsVersion_1_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`
)
@@ -86,8 +92,8 @@ const (
// NewFormat generates a new Format from the type provided. Mostly used for
// tests, most Formats should be generated as part of content negotiation in
// encode.go. If a type has more than one version, the latest version will be
// returned.
// encode.go. If a type has more than one version, the latest stable version will be
// returned, except that TypeTextPlain retains version 0.0.4 for compatibility.
func NewFormat(t FormatType) Format {
switch t {
case TypeProtoCompact:
@@ -107,37 +113,39 @@ func NewFormat(t FormatType) Format {
// NewOpenMetricsFormat generates a new OpenMetrics format matching the
// specified version number.
//
// Note: OpenMetrics versions 2.0.0-rc and 2.0.0 are experimental (supporting
// counter, gauge, summary, untyped, histogram, and gaugehistogram metric types).
func NewOpenMetricsFormat(version string) (Format, error) {
if version == OpenMetricsVersion_0_0_1 {
switch version {
case OpenMetricsVersion_0_0_1:
return FmtOpenMetrics_0_0_1, nil
}
if version == OpenMetricsVersion_1_0_0 {
case OpenMetricsVersion_1_0_0:
return FmtOpenMetrics_1_0_0, nil
case OpenMetricsVersion_2_0_0_rc:
// OpenMetrics 2.0.0-rc is experimental.
return FmtOpenMetrics_2_0_0_rc, nil
case OpenMetricsVersion_2_0_0:
// OpenMetrics 2.0.0 is experimental.
return FmtOpenMetrics_2_0_0, nil
default:
return FmtUnknown, errors.New("unknown open metrics version string")
}
return FmtUnknown, errors.New("unknown open metrics version string")
}
// WithEscapingScheme returns a copy of Format with the specified escaping
// scheme appended to the end. If an escaping scheme already exists it is
// removed.
func (f Format) WithEscapingScheme(s model.EscapingScheme) Format {
var terms []string
for p := range strings.SplitSeq(string(f), ";") {
toks := strings.Split(p, "=")
if len(toks) != 2 {
trimmed := strings.TrimSpace(p)
if len(trimmed) > 0 {
terms = append(terms, trimmed)
}
continue
}
key := strings.TrimSpace(toks[0])
if key != model.EscapingKey {
terms = append(terms, strings.TrimSpace(p))
}
func isOpenMetrics20Version(v string) bool {
return v == OpenMetricsVersion_2_0_0 || v == OpenMetricsVersion_2_0_0_rc
}
// Version returns the version parameter without validating whether it is supported.
// It returns an empty string if the parameter is absent or the Content-Type
// cannot be parsed.
func (f Format) Version() string {
_, params, err := mime.ParseMediaType(string(f))
if err != nil {
return ""
}
terms = append(terms, model.EscapingKey+"="+s.String())
return Format(strings.Join(terms, "; "))
return params["version"]
}
// FormatType deduces an overall FormatType for the given format.
@@ -180,7 +188,7 @@ func (f Format) FormatType() FormatType {
if !ok {
return TypeTextPlain
}
if v == TextVersion {
if v == TextVersion || v == TextVersion_1_0_0 {
return TypeTextPlain
}
return TypeUnknown
@@ -189,8 +197,31 @@ func (f Format) FormatType() FormatType {
}
}
// ToEscapingScheme returns an EscapingScheme depending on the Format. Iff the
// Format contains a escaping=allow-utf-8 term, it will select NoEscaping. If a valid
// WithEscapingScheme returns a copy of Format with the specified escaping
// scheme appended to the end. If an escaping scheme already exists it is
// removed.
func (f Format) WithEscapingScheme(s model.EscapingScheme) Format {
var terms []string
for p := range strings.SplitSeq(string(f), ";") {
toks := strings.Split(p, "=")
if len(toks) != 2 {
trimmed := strings.TrimSpace(p)
if len(trimmed) > 0 {
terms = append(terms, trimmed)
}
continue
}
key := strings.TrimSpace(toks[0])
if key != model.EscapingKey {
terms = append(terms, strings.TrimSpace(p))
}
}
terms = append(terms, model.EscapingKey+"="+s.String())
return Format(strings.Join(terms, "; "))
}
// ToEscapingScheme returns an EscapingScheme depending on the Format. IFF the
// Format contains an escaping=allow-utf-8 term, it will select NoEscaping. If a valid
// "escaping" term exists, that will be used. Otherwise, the global default will
// be returned.
func (f Format) ToEscapingScheme() model.EscapingScheme {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+4 -4
View File
@@ -194,6 +194,7 @@ func (p *TextParser) reset(in io.Reader) {
// start of a line (or whitespace leading up to it).
func (p *TextParser) startOfLine() stateFn {
p.lineCount++
p.currentMetric = nil
p.currentMetricIsInsideBraces = false
p.currentMetricInsideBracesIsPresent = false
if p.skipBlankTab(); p.err != nil {
@@ -339,12 +340,11 @@ func (p *TextParser) startLabelName() stateFn {
return nil // Unexpected end of input.
}
if p.currentByte == '}' {
if p.currentMF == nil {
if p.currentMetric == nil {
// The closing brace was reached before any metric name was read,
// e.g. for the input "{}". There is no metric to attach labels to,
// so this is a malformed exposition. This mirrors the guard in
// startLabelValue. currentMF (not currentMetric) is checked because
// reset only clears currentMF between parses.
// startLabelValue. currentMetric is cleared at the start of each line.
p.parseError("invalid metric name")
p.currentLabelPairs = nil
return nil
@@ -495,7 +495,7 @@ func (p *TextParser) startLabelValue() stateFn {
return p.startLabelName
case '}':
if p.currentMF == nil {
if p.currentMetric == nil {
p.parseError("invalid metric name")
return nil
}