Pārlūkot izejas kodu

vendor: bump prometheus/common v0.7.0

full diff: https://github.com/prometheus/common/compare/7600349dcfe1abd18d72d3a1770870d9800a7801...v0.7.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
Sebastiaan van Stijn 5 gadi atpakaļ
vecāks
revīzija
54dc6f355b

+ 1 - 1
vendor.conf

@@ -146,7 +146,7 @@ code.cloudfoundry.org/clock                         02e53af36e6c978af692887ed449
 github.com/prometheus/client_golang                 c5b7fccd204277076155f10851dad72b76a49317 # v0.8.0
 github.com/beorn7/perks                             37c8de3658fcb183f997c4e13e8337516ab753e6 # v1.0.1
 github.com/prometheus/client_model                  d1d2010b5beead3fa1c5f271a5cf626e40b3ad6e # v0.1.0
-github.com/prometheus/common                        7600349dcfe1abd18d72d3a1770870d9800a7801
+github.com/prometheus/common                        287d3e634a1e550c9e463dd7e5a75a422c614505 # v0.7.0
 github.com/prometheus/procfs                        7d6f385de8bea29190f15ba9931442a0eaef9af7
 github.com/matttproud/golang_protobuf_extensions    c12348ce28de40eed0136aa2b644d0ee0650e56c # v1.0.1
 github.com/pkg/errors                               ba968bfe8b2f7e042a574c888954fccecfa385b4 # v0.8.1

+ 5 - 1
vendor/github.com/prometheus/common/README.md

@@ -6,7 +6,11 @@ components and libraries.
 
 * **config**: Common configuration structures
 * **expfmt**: Decoding and encoding for the exposition format
-* **log**: A logging wrapper around [logrus](https://github.com/sirupsen/logrus)
 * **model**: Shared data structures
+* **promlog**: A logging wrapper around [go-kit/log](https://github.com/go-kit/kit/tree/master/log)
 * **route**: A routing wrapper around [httprouter](https://github.com/julienschmidt/httprouter) using `context.Context`
+* **server**: Common servers
 * **version**: Version information and metrics
+
+## Deprecated
+* **log**: A logging wrapper around [logrus](https://github.com/sirupsen/logrus)

+ 259 - 96
vendor/github.com/prometheus/common/expfmt/text_create.go

@@ -14,13 +14,45 @@
 package expfmt
 
 import (
+	"bufio"
 	"fmt"
 	"io"
+	"io/ioutil"
 	"math"
+	"strconv"
 	"strings"
+	"sync"
 
-	dto "github.com/prometheus/client_model/go"
 	"github.com/prometheus/common/model"
+
+	dto "github.com/prometheus/client_model/go"
+)
+
+// enhancedWriter has all the enhanced write functions needed here. bufio.Writer
+// implements it.
+type enhancedWriter interface {
+	io.Writer
+	WriteRune(r rune) (n int, err error)
+	WriteString(s string) (n int, err error)
+	WriteByte(c byte) error
+}
+
+const (
+	initialNumBufSize = 24
+)
+
+var (
+	bufPool = sync.Pool{
+		New: func() interface{} {
+			return bufio.NewWriter(ioutil.Discard)
+		},
+	}
+	numBufPool = sync.Pool{
+		New: func() interface{} {
+			b := make([]byte, 0, initialNumBufSize)
+			return &b
+		},
+	}
 )
 
 // MetricFamilyToText converts a MetricFamily proto message into text format and
@@ -32,37 +64,90 @@ import (
 // will result in invalid text format output.
 //
 // This method fulfills the type 'prometheus.encoder'.
-func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (int, error) {
-	var written int
-
+func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (written int, err error) {
 	// Fail-fast checks.
 	if len(in.Metric) == 0 {
-		return written, fmt.Errorf("MetricFamily has no metrics: %s", in)
+		return 0, fmt.Errorf("MetricFamily has no metrics: %s", in)
 	}
 	name := in.GetName()
 	if name == "" {
-		return written, fmt.Errorf("MetricFamily has no name: %s", in)
+		return 0, fmt.Errorf("MetricFamily has no name: %s", in)
+	}
+
+	// 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
+
 	// Comments, first HELP, then TYPE.
 	if in.Help != nil {
-		n, err := fmt.Fprintf(
-			out, "# HELP %s %s\n",
-			name, escapeString(*in.Help, false),
-		)
+		n, err = w.WriteString("# HELP ")
 		written += n
 		if err != nil {
-			return written, err
+			return
+		}
+		n, err = w.WriteString(name)
+		written += n
+		if err != nil {
+			return
+		}
+		err = w.WriteByte(' ')
+		written++
+		if err != nil {
+			return
 		}
+		n, err = writeEscapedString(w, *in.Help, false)
+		written += n
+		if err != nil {
+			return
+		}
+		err = w.WriteByte('\n')
+		written++
+		if err != nil {
+			return
+		}
+	}
+	n, err = w.WriteString("# TYPE ")
+	written += n
+	if err != nil {
+		return
+	}
+	n, err = w.WriteString(name)
+	written += n
+	if err != nil {
+		return
 	}
 	metricType := in.GetType()
-	n, err := fmt.Fprintf(
-		out, "# TYPE %s %s\n",
-		name, strings.ToLower(metricType.String()),
-	)
+	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(" untyped\n")
+	case dto.MetricType_HISTOGRAM:
+		n, err = w.WriteString(" histogram\n")
+	default:
+		return written, fmt.Errorf("unknown metric type %s", metricType.String())
+	}
 	written += n
 	if err != nil {
-		return written, err
+		return
 	}
 
 	// Finally the samples, one line for each.
@@ -75,9 +160,8 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (int, error) {
 				)
 			}
 			n, err = writeSample(
-				name, metric, "", "",
+				w, name, "", metric, "", 0,
 				metric.Counter.GetValue(),
-				out,
 			)
 		case dto.MetricType_GAUGE:
 			if metric.Gauge == nil {
@@ -86,9 +170,8 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (int, error) {
 				)
 			}
 			n, err = writeSample(
-				name, metric, "", "",
+				w, name, "", metric, "", 0,
 				metric.Gauge.GetValue(),
-				out,
 			)
 		case dto.MetricType_UNTYPED:
 			if metric.Untyped == nil {
@@ -97,9 +180,8 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (int, error) {
 				)
 			}
 			n, err = writeSample(
-				name, metric, "", "",
+				w, name, "", metric, "", 0,
 				metric.Untyped.GetValue(),
-				out,
 			)
 		case dto.MetricType_SUMMARY:
 			if metric.Summary == nil {
@@ -109,29 +191,26 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (int, error) {
 			}
 			for _, q := range metric.Summary.Quantile {
 				n, err = writeSample(
-					name, metric,
-					model.QuantileLabel, fmt.Sprint(q.GetQuantile()),
+					w, name, "", metric,
+					model.QuantileLabel, q.GetQuantile(),
 					q.GetValue(),
-					out,
 				)
 				written += n
 				if err != nil {
-					return written, err
+					return
 				}
 			}
 			n, err = writeSample(
-				name+"_sum", metric, "", "",
+				w, name, "_sum", metric, "", 0,
 				metric.Summary.GetSampleSum(),
-				out,
 			)
+			written += n
 			if err != nil {
-				return written, err
+				return
 			}
-			written += n
 			n, err = writeSample(
-				name+"_count", metric, "", "",
+				w, name, "_count", metric, "", 0,
 				float64(metric.Summary.GetSampleCount()),
-				out,
 			)
 		case dto.MetricType_HISTOGRAM:
 			if metric.Histogram == nil {
@@ -140,46 +219,42 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (int, error) {
 				)
 			}
 			infSeen := false
-			for _, q := range metric.Histogram.Bucket {
+			for _, b := range metric.Histogram.Bucket {
 				n, err = writeSample(
-					name+"_bucket", metric,
-					model.BucketLabel, fmt.Sprint(q.GetUpperBound()),
-					float64(q.GetCumulativeCount()),
-					out,
+					w, name, "_bucket", metric,
+					model.BucketLabel, b.GetUpperBound(),
+					float64(b.GetCumulativeCount()),
 				)
 				written += n
 				if err != nil {
-					return written, err
+					return
 				}
-				if math.IsInf(q.GetUpperBound(), +1) {
+				if math.IsInf(b.GetUpperBound(), +1) {
 					infSeen = true
 				}
 			}
 			if !infSeen {
 				n, err = writeSample(
-					name+"_bucket", metric,
-					model.BucketLabel, "+Inf",
+					w, name, "_bucket", metric,
+					model.BucketLabel, math.Inf(+1),
 					float64(metric.Histogram.GetSampleCount()),
-					out,
 				)
+				written += n
 				if err != nil {
-					return written, err
+					return
 				}
-				written += n
 			}
 			n, err = writeSample(
-				name+"_sum", metric, "", "",
+				w, name, "_sum", metric, "", 0,
 				metric.Histogram.GetSampleSum(),
-				out,
 			)
+			written += n
 			if err != nil {
-				return written, err
+				return
 			}
-			written += n
 			n, err = writeSample(
-				name+"_count", metric, "", "",
+				w, name, "_count", metric, "", 0,
 				float64(metric.Histogram.GetSampleCount()),
-				out,
 			)
 		default:
 			return written, fmt.Errorf(
@@ -188,116 +263,204 @@ func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (int, error) {
 		}
 		written += n
 		if err != nil {
-			return written, err
+			return
 		}
 	}
-	return written, nil
+	return
 }
 
-// writeSample writes a single sample in text format to out, given the metric
+// writeSample writes a single sample in text format to w, given the metric
 // name, the metric proto message itself, optionally an additional label name
-// and value (use empty strings if not required), and the value. The function
-// returns the number of bytes written and any error encountered.
+// with a float64 value (use empty string as label name if not required), and
+// the value. The function returns the number of bytes written and any error
+// encountered.
 func writeSample(
-	name string,
+	w enhancedWriter,
+	name, suffix string,
 	metric *dto.Metric,
-	additionalLabelName, additionalLabelValue string,
+	additionalLabelName string, additionalLabelValue float64,
 	value float64,
-	out io.Writer,
 ) (int, error) {
 	var written int
-	n, err := fmt.Fprint(out, name)
+	n, err := w.WriteString(name)
 	written += n
 	if err != nil {
 		return written, err
 	}
-	n, err = labelPairsToText(
-		metric.Label,
-		additionalLabelName, additionalLabelValue,
-		out,
+	if suffix != "" {
+		n, err = w.WriteString(suffix)
+		written += n
+		if err != nil {
+			return written, err
+		}
+	}
+	n, err = writeLabelPairs(
+		w, metric.Label, additionalLabelName, additionalLabelValue,
 	)
 	written += n
 	if err != nil {
 		return written, err
 	}
-	n, err = fmt.Fprintf(out, " %v", value)
+	err = w.WriteByte(' ')
+	written++
+	if err != nil {
+		return written, err
+	}
+	n, err = writeFloat(w, value)
 	written += n
 	if err != nil {
 		return written, err
 	}
 	if metric.TimestampMs != nil {
-		n, err = fmt.Fprintf(out, " %v", *metric.TimestampMs)
+		err = w.WriteByte(' ')
+		written++
+		if err != nil {
+			return written, err
+		}
+		n, err = writeInt(w, *metric.TimestampMs)
 		written += n
 		if err != nil {
 			return written, err
 		}
 	}
-	n, err = out.Write([]byte{'\n'})
-	written += n
+	err = w.WriteByte('\n')
+	written++
 	if err != nil {
 		return written, err
 	}
 	return written, nil
 }
 
-// labelPairsToText converts a slice of LabelPair proto messages plus the
+// writeLabelPairs converts a slice of LabelPair proto messages plus the
 // explicitly given additional label pair into text formatted as required by the
-// text format and writes it to 'out'. An empty slice in combination with an
-// empty string 'additionalLabelName' results in nothing being
-// written. Otherwise, the label pairs are written, escaped as required by the
-// text format, and enclosed in '{...}'. The function returns the number of
-// bytes written and any error encountered.
-func labelPairsToText(
+// text format and writes it to 'w'. An empty slice in combination with an empty
+// string 'additionalLabelName' results in nothing being written. Otherwise, the
+// label pairs are written, escaped as required by the text format, and enclosed
+// in '{...}'. The function returns the number of bytes written and any error
+// encountered.
+func writeLabelPairs(
+	w enhancedWriter,
 	in []*dto.LabelPair,
-	additionalLabelName, additionalLabelValue string,
-	out io.Writer,
+	additionalLabelName string, additionalLabelValue float64,
 ) (int, error) {
 	if len(in) == 0 && additionalLabelName == "" {
 		return 0, nil
 	}
-	var written int
-	separator := '{'
+	var (
+		written   int
+		separator byte = '{'
+	)
 	for _, lp := range in {
-		n, err := fmt.Fprintf(
-			out, `%c%s="%s"`,
-			separator, lp.GetName(), escapeString(lp.GetValue(), true),
-		)
+		err := w.WriteByte(separator)
+		written++
+		if err != nil {
+			return written, err
+		}
+		n, err := w.WriteString(lp.GetName())
+		written += n
+		if err != nil {
+			return written, err
+		}
+		n, err = w.WriteString(`="`)
+		written += n
+		if err != nil {
+			return written, err
+		}
+		n, err = writeEscapedString(w, lp.GetValue(), true)
 		written += n
 		if err != nil {
 			return written, err
 		}
+		err = w.WriteByte('"')
+		written++
+		if err != nil {
+			return written, err
+		}
 		separator = ','
 	}
 	if additionalLabelName != "" {
-		n, err := fmt.Fprintf(
-			out, `%c%s="%s"`,
-			separator, additionalLabelName,
-			escapeString(additionalLabelValue, true),
-		)
+		err := w.WriteByte(separator)
+		written++
+		if err != nil {
+			return written, err
+		}
+		n, err := w.WriteString(additionalLabelName)
+		written += n
+		if err != nil {
+			return written, err
+		}
+		n, err = w.WriteString(`="`)
+		written += n
+		if err != nil {
+			return written, err
+		}
+		n, err = writeFloat(w, additionalLabelValue)
 		written += n
 		if err != nil {
 			return written, err
 		}
+		err = w.WriteByte('"')
+		written++
+		if err != nil {
+			return written, err
+		}
 	}
-	n, err := out.Write([]byte{'}'})
-	written += n
+	err := w.WriteByte('}')
+	written++
 	if err != nil {
 		return written, err
 	}
 	return written, nil
 }
 
+// writeEscapedString replaces '\' by '\\', new line character by '\n', and - if
+// includeDoubleQuote is true - '"' by '\"'.
 var (
-	escape                = strings.NewReplacer("\\", `\\`, "\n", `\n`)
-	escapeWithDoubleQuote = strings.NewReplacer("\\", `\\`, "\n", `\n`, "\"", `\"`)
+	escaper       = strings.NewReplacer("\\", `\\`, "\n", `\n`)
+	quotedEscaper = strings.NewReplacer("\\", `\\`, "\n", `\n`, "\"", `\"`)
 )
 
-// escapeString replaces '\' by '\\', new line character by '\n', and - if
-// includeDoubleQuote is true - '"' by '\"'.
-func escapeString(v string, includeDoubleQuote bool) string {
+func writeEscapedString(w enhancedWriter, v string, includeDoubleQuote bool) (int, error) {
 	if includeDoubleQuote {
-		return escapeWithDoubleQuote.Replace(v)
+		return quotedEscaper.WriteString(w, v)
+	} else {
+		return escaper.WriteString(w, v)
+	}
+}
+
+// writeFloat is equivalent to fmt.Fprint with a float64 argument but hardcodes
+// a few common cases for increased efficiency. For non-hardcoded cases, it uses
+// strconv.AppendFloat to avoid allocations, similar to writeInt.
+func writeFloat(w enhancedWriter, f float64) (int, error) {
+	switch {
+	case f == 1:
+		return 1, w.WriteByte('1')
+	case f == 0:
+		return 1, w.WriteByte('0')
+	case f == -1:
+		return w.WriteString("-1")
+	case math.IsNaN(f):
+		return w.WriteString("NaN")
+	case math.IsInf(f, +1):
+		return w.WriteString("+Inf")
+	case math.IsInf(f, -1):
+		return w.WriteString("-Inf")
+	default:
+		bp := numBufPool.Get().(*[]byte)
+		*bp = strconv.AppendFloat((*bp)[:0], f, 'g', -1, 64)
+		written, err := w.Write(*bp)
+		numBufPool.Put(bp)
+		return written, err
 	}
+}
 
-	return escape.Replace(v)
+// writeInt is equivalent to fmt.Fprint with an int64 argument but uses
+// strconv.AppendInt with a byte slice taken from a sync.Pool to avoid
+// allocations.
+func writeInt(w enhancedWriter, i int64) (int, error) {
+	bp := numBufPool.Get().(*[]byte)
+	*bp = strconv.AppendInt((*bp)[:0], i, 10)
+	written, err := w.Write(*bp)
+	numBufPool.Put(bp)
+	return written, err
 }

+ 11 - 4
vendor/github.com/prometheus/common/expfmt/text_parse.go

@@ -325,7 +325,7 @@ func (p *TextParser) startLabelValue() stateFn {
 	// - Other labels have to be added to currentLabels for signature calculation.
 	if p.currentMF.GetType() == dto.MetricType_SUMMARY {
 		if p.currentLabelPair.GetName() == model.QuantileLabel {
-			if p.currentQuantile, p.err = strconv.ParseFloat(p.currentLabelPair.GetValue(), 64); p.err != nil {
+			if p.currentQuantile, p.err = parseFloat(p.currentLabelPair.GetValue()); p.err != nil {
 				// Create a more helpful error message.
 				p.parseError(fmt.Sprintf("expected float as value for 'quantile' label, got %q", p.currentLabelPair.GetValue()))
 				return nil
@@ -337,7 +337,7 @@ func (p *TextParser) startLabelValue() stateFn {
 	// Similar special treatment of histograms.
 	if p.currentMF.GetType() == dto.MetricType_HISTOGRAM {
 		if p.currentLabelPair.GetName() == model.BucketLabel {
-			if p.currentBucket, p.err = strconv.ParseFloat(p.currentLabelPair.GetValue(), 64); p.err != nil {
+			if p.currentBucket, p.err = parseFloat(p.currentLabelPair.GetValue()); p.err != nil {
 				// Create a more helpful error message.
 				p.parseError(fmt.Sprintf("expected float as value for 'le' label, got %q", p.currentLabelPair.GetValue()))
 				return nil
@@ -359,7 +359,7 @@ func (p *TextParser) startLabelValue() stateFn {
 		}
 		return p.readingValue
 	default:
-		p.parseError(fmt.Sprintf("unexpected end of label value %q", p.currentLabelPair.Value))
+		p.parseError(fmt.Sprintf("unexpected end of label value %q", p.currentLabelPair.GetValue()))
 		return nil
 	}
 }
@@ -392,7 +392,7 @@ func (p *TextParser) readingValue() stateFn {
 	if p.readTokenUntilWhitespace(); p.err != nil {
 		return nil // Unexpected end of input.
 	}
-	value, err := strconv.ParseFloat(p.currentToken.String(), 64)
+	value, err := parseFloat(p.currentToken.String())
 	if err != nil {
 		// Create a more helpful error message.
 		p.parseError(fmt.Sprintf("expected float as value, got %q", p.currentToken.String()))
@@ -755,3 +755,10 @@ func histogramMetricName(name string) string {
 		return name
 	}
 }
+
+func parseFloat(s string) (float64, error) {
+	if strings.ContainsAny(s, "pP_") {
+		return 0, fmt.Errorf("unsupported character in float")
+	}
+	return strconv.ParseFloat(s, 64)
+}

+ 22 - 0
vendor/github.com/prometheus/common/go.mod

@@ -0,0 +1,22 @@
+module github.com/prometheus/common
+
+require (
+	github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751 // indirect
+	github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4 // indirect
+	github.com/go-kit/kit v0.9.0
+	github.com/go-logfmt/logfmt v0.4.0 // indirect
+	github.com/golang/protobuf v1.3.2
+	github.com/julienschmidt/httprouter v1.2.0
+	github.com/matttproud/golang_protobuf_extensions v1.0.1
+	github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223
+	github.com/pkg/errors v0.8.1
+	github.com/prometheus/client_golang v1.0.0
+	github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90
+	github.com/sirupsen/logrus v1.4.2
+	golang.org/x/net v0.0.0-20190613194153-d28f0bde5980 // indirect
+	golang.org/x/sys v0.0.0-20190422165155-953cdadca894
+	gopkg.in/alecthomas/kingpin.v2 v2.2.6
+	gopkg.in/yaml.v2 v2.2.2
+)
+
+go 1.11

+ 3 - 3
vendor/github.com/prometheus/common/internal/bitbucket.org/ww/goautoneg/autoneg.go

@@ -1,12 +1,12 @@
 /*
+Copyright (c) 2011, Open Knowledge Foundation Ltd.
+All rights reserved.
+
 HTTP Content-Type Autonegotiation.
 
 The functions in this package implement the behaviour specified in
 http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
 
-Copyright (c) 2011, Open Knowledge Foundation Ltd.
-All rights reserved.
-
 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are
 met:

+ 0 - 1
vendor/github.com/prometheus/common/model/metric.go

@@ -21,7 +21,6 @@ import (
 )
 
 var (
-	separator = []byte{0}
 	// MetricNameRE is a regular expression matching valid metric
 	// names. Note that the IsValidMetricName function performs the same
 	// check but faster than a match with this regular expression.

+ 8 - 2
vendor/github.com/prometheus/common/model/time.go

@@ -43,7 +43,7 @@ const (
 // (1970-01-01 00:00 UTC) excluding leap seconds.
 type Time int64
 
-// Interval describes and interval between two timestamps.
+// Interval describes an interval between two timestamps.
 type Interval struct {
 	Start, End Time
 }
@@ -150,7 +150,13 @@ func (t *Time) UnmarshalJSON(b []byte) error {
 			return err
 		}
 
-		*t = Time(v + va)
+		// If the value was something like -0.1 the negative is lost in the
+		// parsing because of the leading zero, this ensures that we capture it.
+		if len(p[0]) > 0 && p[0][0] == '-' && v+va > 0 {
+			*t = Time(v+va) * -1
+		} else {
+			*t = Time(v + va)
+		}
 
 	default:
 		return fmt.Errorf("invalid time %q", string(b))