| 1 |
// Copyright 2014 The Prometheus Authors |
| 2 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 |
// you may not use this file except in compliance with the License. |
| 4 |
// You may obtain a copy of the License at |
| 5 |
// |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package prometheus |
| 15 |
|
| 16 |
import ( |
| 17 |
"errors" |
| 18 |
"math" |
| 19 |
"sort" |
| 20 |
"strings" |
| 21 |
"time" |
| 22 |
|
| 23 |
dto "github.com/prometheus/client_model/go" |
| 24 |
"github.com/prometheus/common/model" |
| 25 |
"google.golang.org/protobuf/proto" |
| 26 |
) |
| 27 |
|
| 28 |
var separatorByteSlice = []byte{model.SeparatorByte} // For convenient use with xxhash. |
| 29 |
|
| 30 |
// A Metric models a single sample value with its meta data being exported to |
| 31 |
// Prometheus. Implementations of Metric in this package are Gauge, Counter, |
| 32 |
// Histogram, Summary, and Untyped. |
| 33 |
type Metric interface { |
| 34 |
// Desc returns the descriptor for the Metric. This method idempotently |
| 35 |
// returns the same descriptor throughout the lifetime of the |
| 36 |
// Metric. The returned descriptor is immutable by contract. A Metric |
| 37 |
// unable to describe itself must return an invalid descriptor (created |
| 38 |
// with NewInvalidDesc). |
| 39 |
Desc() *Desc |
| 40 |
// Write encodes the Metric into a "Metric" Protocol Buffer data |
| 41 |
// transmission object. |
| 42 |
// |
| 43 |
// Metric implementations must observe concurrency safety as reads of |
| 44 |
// this metric may occur at any time, and any blocking occurs at the |
| 45 |
// expense of total performance of rendering all registered |
| 46 |
// metrics. Ideally, Metric implementations should support concurrent |
| 47 |
// readers. |
| 48 |
// |
| 49 |
// While populating dto.Metric, it is the responsibility of the |
| 50 |
// implementation to ensure validity of the Metric protobuf (like valid |
| 51 |
// UTF-8 strings or syntactically valid metric and label names). It is |
| 52 |
// recommended to sort labels lexicographically. Callers of Write should |
| 53 |
// still make sure of sorting if they depend on it. |
| 54 |
Write(*dto.Metric) error |
| 55 |
// TODO(beorn7): The original rationale of passing in a pre-allocated |
| 56 |
// dto.Metric protobuf to save allocations has disappeared. The |
| 57 |
// signature of this method should be changed to "Write() (*dto.Metric, |
| 58 |
// error)". |
| 59 |
} |
| 60 |
|
| 61 |
// Opts bundles the options for creating most Metric types. Each metric |
| 62 |
// implementation XXX has its own XXXOpts type, but in most cases, it is just |
| 63 |
// an alias of this type (which might change when the requirement arises.) |
| 64 |
// |
| 65 |
// It is mandatory to set Name to a non-empty string. All other fields are |
| 66 |
// optional and can safely be left at their zero value, although it is strongly |
| 67 |
// encouraged to set a Help string. |
| 68 |
type Opts struct { |
| 69 |
// Namespace, Subsystem, and Name are components of the fully-qualified |
| 70 |
// name of the Metric (created by joining these components with |
| 71 |
// "_"). Only Name is mandatory, the others merely help structuring the |
| 72 |
// name. Note that the fully-qualified name of the metric must be a |
| 73 |
// valid Prometheus metric name. |
| 74 |
Namespace string |
| 75 |
Subsystem string |
| 76 |
Name string |
| 77 |
|
| 78 |
// Help provides information about this metric. |
| 79 |
// |
| 80 |
// Metrics with the same fully-qualified name must have the same Help |
| 81 |
// string. |
| 82 |
Help string |
| 83 |
|
| 84 |
// ConstLabels are used to attach fixed labels to this metric. Metrics |
| 85 |
// with the same fully-qualified name must have the same label names in |
| 86 |
// their ConstLabels. |
| 87 |
// |
| 88 |
// ConstLabels are only used rarely. In particular, do not use them to |
| 89 |
// attach the same labels to all your metrics. Those use cases are |
| 90 |
// better covered by target labels set by the scraping Prometheus |
| 91 |
// server, or by one specific metric (e.g. a build_info or a |
| 92 |
// machine_role metric). See also |
| 93 |
// https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels-not-static-scraped-labels |
| 94 |
ConstLabels Labels |
| 95 |
|
| 96 |
// now is for testing purposes, by default it's time.Now. |
| 97 |
now func() time.Time |
| 98 |
} |
| 99 |
|
| 100 |
// BuildFQName joins the given three name components by "_". Empty name |
| 101 |
// components are ignored. If the name parameter itself is empty, an empty |
| 102 |
// string is returned, no matter what. Metric implementations included in this |
| 103 |
// library use this function internally to generate the fully-qualified metric |
| 104 |
// name from the name component in their Opts. Users of the library will only |
| 105 |
// need this function if they implement their own Metric or instantiate a Desc |
| 106 |
// (with NewDesc) directly. |
| 107 |
func BuildFQName(namespace, subsystem, name string) string { |
| 108 |
if name == "" { |
| 109 |
return "" |
| 110 |
} |
| 111 |
|
| 112 |
sb := strings.Builder{} |
| 113 |
sb.Grow(len(namespace) + len(subsystem) + len(name) + 2) |
| 114 |
|
| 115 |
if namespace != "" { |
| 116 |
sb.WriteString(namespace) |
| 117 |
sb.WriteString("_") |
| 118 |
} |
| 119 |
|
| 120 |
if subsystem != "" { |
| 121 |
sb.WriteString(subsystem) |
| 122 |
sb.WriteString("_") |
| 123 |
} |
| 124 |
|
| 125 |
sb.WriteString(name) |
| 126 |
|
| 127 |
return sb.String() |
| 128 |
} |
| 129 |
|
| 130 |
type invalidMetric struct { |
| 131 |
desc *Desc |
| 132 |
err error |
| 133 |
} |
| 134 |
|
| 135 |
// NewInvalidMetric returns a metric whose Write method always returns the |
| 136 |
// provided error. It is useful if a Collector finds itself unable to collect |
| 137 |
// a metric and wishes to report an error to the registry. |
| 138 |
func NewInvalidMetric(desc *Desc, err error) Metric { |
| 139 |
return &invalidMetric{desc, err} |
| 140 |
} |
| 141 |
|
| 142 |
func (m *invalidMetric) Desc() *Desc { return m.desc } |
| 143 |
|
| 144 |
func (m *invalidMetric) Write(*dto.Metric) error { return m.err } |
| 145 |
|
| 146 |
type timestampedMetric struct { |
| 147 |
Metric |
| 148 |
t time.Time |
| 149 |
} |
| 150 |
|
| 151 |
func (m timestampedMetric) Write(pb *dto.Metric) error { |
| 152 |
e := m.Metric.Write(pb) |
| 153 |
pb.TimestampMs = proto.Int64(m.t.Unix()*1000 + int64(m.t.Nanosecond()/1000000)) |
| 154 |
return e |
| 155 |
} |
| 156 |
|
| 157 |
// NewMetricWithTimestamp returns a new Metric wrapping the provided Metric in a |
| 158 |
// way that it has an explicit timestamp set to the provided Time. This is only |
| 159 |
// useful in rare cases as the timestamp of a Prometheus metric should usually |
| 160 |
// be set by the Prometheus server during scraping. Exceptions include mirroring |
| 161 |
// metrics with given timestamps from other metric |
| 162 |
// sources. |
| 163 |
// |
| 164 |
// NewMetricWithTimestamp works best with MustNewConstMetric, |
| 165 |
// MustNewConstHistogram, and MustNewConstSummary, see example. |
| 166 |
// |
| 167 |
// Currently, the exposition formats used by Prometheus are limited to |
| 168 |
// millisecond resolution. Thus, the provided time will be rounded down to the |
| 169 |
// next full millisecond value. |
| 170 |
func NewMetricWithTimestamp(t time.Time, m Metric) Metric { |
| 171 |
return timestampedMetric{Metric: m, t: t} |
| 172 |
} |
| 173 |
|
| 174 |
type withExemplarsMetric struct { |
| 175 |
Metric |
| 176 |
|
| 177 |
exemplars []*dto.Exemplar |
| 178 |
} |
| 179 |
|
| 180 |
func (m *withExemplarsMetric) Write(pb *dto.Metric) error { |
| 181 |
if err := m.Metric.Write(pb); err != nil { |
| 182 |
return err |
| 183 |
} |
| 184 |
|
| 185 |
switch { |
| 186 |
case pb.Counter != nil: |
| 187 |
pb.Counter.Exemplar = m.exemplars[len(m.exemplars)-1] |
| 188 |
case pb.Histogram != nil: |
| 189 |
h := pb.Histogram |
| 190 |
for _, e := range m.exemplars { |
| 191 |
if (h.GetZeroThreshold() != 0 || h.GetZeroCount() != 0 || |
| 192 |
len(h.PositiveSpan) != 0 || len(h.NegativeSpan) != 0) && |
| 193 |
e.GetTimestamp() != nil { |
| 194 |
h.Exemplars = append(h.Exemplars, e) |
| 195 |
if len(h.Bucket) == 0 { |
| 196 |
// Don't proceed to classic buckets if there are none. |
| 197 |
continue |
| 198 |
} |
| 199 |
} |
| 200 |
// h.Bucket are sorted by UpperBound. |
| 201 |
i := sort.Search(len(h.Bucket), func(i int) bool { |
| 202 |
return h.Bucket[i].GetUpperBound() >= e.GetValue() |
| 203 |
}) |
| 204 |
if i < len(h.Bucket) { |
| 205 |
h.Bucket[i].Exemplar = e |
| 206 |
} else { |
| 207 |
// The +Inf bucket should be explicitly added if there is an exemplar for it, similar to non-const histogram logic in https://github.com/prometheus/client_golang/blob/main/prometheus/histogram.go#L357-L365. |
| 208 |
b := &dto.Bucket{ |
| 209 |
CumulativeCount: proto.Uint64(h.GetSampleCount()), |
| 210 |
UpperBound: proto.Float64(math.Inf(1)), |
| 211 |
Exemplar: e, |
| 212 |
} |
| 213 |
h.Bucket = append(h.Bucket, b) |
| 214 |
} |
| 215 |
} |
| 216 |
default: |
| 217 |
// TODO(bwplotka): Implement Gauge? |
| 218 |
return errors.New("cannot inject exemplar into Gauge, Summary or Untyped") |
| 219 |
} |
| 220 |
|
| 221 |
return nil |
| 222 |
} |
| 223 |
|
| 224 |
// Exemplar is easier to use, user-facing representation of *dto.Exemplar. |
| 225 |
type Exemplar struct { |
| 226 |
Value float64 |
| 227 |
Labels Labels |
| 228 |
// Optional. |
| 229 |
// Default value (time.Time{}) indicates its empty, which should be |
| 230 |
// understood as time.Now() time at the moment of creation of metric. |
| 231 |
Timestamp time.Time |
| 232 |
} |
| 233 |
|
| 234 |
// NewMetricWithExemplars returns a new Metric wrapping the provided Metric with given |
| 235 |
// exemplars. Exemplars are validated. |
| 236 |
// |
| 237 |
// Only last applicable exemplar is injected from the list. |
| 238 |
// For example for Counter it means last exemplar is injected. |
| 239 |
// For Histogram, it means last applicable exemplar for each bucket is injected. |
| 240 |
// For a Native Histogram, all valid exemplars are injected. |
| 241 |
// |
| 242 |
// NewMetricWithExemplars works best with MustNewConstMetric and |
| 243 |
// MustNewConstHistogram, see example. |
| 244 |
func NewMetricWithExemplars(m Metric, exemplars ...Exemplar) (Metric, error) { |
| 245 |
if len(exemplars) == 0 { |
| 246 |
return nil, errors.New("no exemplar was passed for NewMetricWithExemplars") |
| 247 |
} |
| 248 |
|
| 249 |
var ( |
| 250 |
now = time.Now() |
| 251 |
exs = make([]*dto.Exemplar, len(exemplars)) |
| 252 |
err error |
| 253 |
) |
| 254 |
for i, e := range exemplars { |
| 255 |
ts := e.Timestamp |
| 256 |
if ts.IsZero() { |
| 257 |
ts = now |
| 258 |
} |
| 259 |
exs[i], err = newExemplar(e.Value, ts, e.Labels) |
| 260 |
if err != nil { |
| 261 |
return nil, err |
| 262 |
} |
| 263 |
} |
| 264 |
|
| 265 |
return &withExemplarsMetric{Metric: m, exemplars: exs}, nil |
| 266 |
} |
| 267 |
|
| 268 |
// MustNewMetricWithExemplars is a version of NewMetricWithExemplars that panics where |
| 269 |
// NewMetricWithExemplars would have returned an error. |
| 270 |
func MustNewMetricWithExemplars(m Metric, exemplars ...Exemplar) Metric { |
| 271 |
ret, err := NewMetricWithExemplars(m, exemplars...) |
| 272 |
if err != nil { |
| 273 |
panic(err) |
| 274 |
} |
| 275 |
return ret |
| 276 |
} |