2 Copyright 2018 The Kubernetes Authors All rights reserved.
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
8 http://www.apache.org/licenses/LICENSE-2.0
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
28 initialNumBufSize = 24
32 numBufPool = sync.Pool{
33 New: func() interface{} {
34 b := make([]byte, 0, initialNumBufSize)
40 // Type represents the type of a metric e.g. a counter. See
41 // https://prometheus.io/docs/concepts/metric_types/.
44 // Gauge defines a Prometheus gauge.
45 var Gauge Type = "gauge"
47 // Counter defines a Prometheus counter.
48 var Counter Type = "counter"
50 // Metric represents a single time series.
52 // The name of a metric is injected by its family to reduce duplication.
58 func (m *Metric) Write(s *strings.Builder) {
59 if len(m.LabelKeys) != len(m.LabelValues) {
61 "expected labelKeys %q to be of same length as labelValues %q",
62 m.LabelKeys, m.LabelValues,
66 labelsToString(s, m.LabelKeys, m.LabelValues)
68 writeFloat(s, m.Value)
72 func labelsToString(m *strings.Builder, keys, values []string) {
74 var separator byte = '{'
76 for i := 0; i < len(keys); i++ {
77 m.WriteByte(separator)
78 m.WriteString(keys[i])
80 escapeString(m, values[i])
90 escapeWithDoubleQuote = strings.NewReplacer("\\", `\\`, "\n", `\n`, "\"", `\"`)
93 // escapeString replaces '\' by '\\', new line character by '\n', and '"' by
95 // Taken from github.com/prometheus/common/expfmt/text_create.go.
96 func escapeString(m *strings.Builder, v string) {
97 escapeWithDoubleQuote.WriteString(m, v)
100 // writeFloat is equivalent to fmt.Fprint with a float64 argument but hardcodes
101 // a few common cases for increased efficiency. For non-hardcoded cases, it uses
102 // strconv.AppendFloat to avoid allocations, similar to writeInt.
103 // Taken from github.com/prometheus/common/expfmt/text_create.go.
104 func writeFloat(w *strings.Builder, f float64) {
114 case math.IsInf(f, +1):
115 w.WriteString("+Inf")
116 case math.IsInf(f, -1):
117 w.WriteString("-Inf")
119 bp := numBufPool.Get().(*[]byte)
120 *bp = strconv.AppendFloat((*bp)[:0], f, 'g', -1, 64)