| 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 |
"sync/atomic" |
| 20 |
"time" |
| 21 |
|
| 22 |
dto "github.com/prometheus/client_model/go" |
| 23 |
"google.golang.org/protobuf/types/known/timestamppb" |
| 24 |
) |
| 25 |
|
| 26 |
// Counter is a Metric that represents a single numerical value that only ever |
| 27 |
// goes up. That implies that it cannot be used to count items whose number can |
| 28 |
// also go down, e.g. the number of currently running goroutines. Those |
| 29 |
// "counters" are represented by Gauges. |
| 30 |
// |
| 31 |
// A Counter is typically used to count requests served, tasks completed, errors |
| 32 |
// occurred, etc. |
| 33 |
// |
| 34 |
// To create Counter instances, use NewCounter. |
| 35 |
type Counter interface { |
| 36 |
Metric |
| 37 |
Collector |
| 38 |
|
| 39 |
// Inc increments the counter by 1. Use Add to increment it by arbitrary |
| 40 |
// non-negative values. |
| 41 |
Inc() |
| 42 |
// Add adds the given value to the counter. It panics if the value is < |
| 43 |
// 0. |
| 44 |
Add(float64) |
| 45 |
} |
| 46 |
|
| 47 |
// ExemplarAdder is implemented by Counters that offer the option of adding a |
| 48 |
// value to the Counter together with an exemplar. Its AddWithExemplar method |
| 49 |
// works like the Add method of the Counter interface but also replaces the |
| 50 |
// currently saved exemplar (if any) with a new one, created from the provided |
| 51 |
// value, the current time as timestamp, and the provided labels. Empty Labels |
| 52 |
// will lead to a valid (label-less) exemplar. But if Labels is nil, the current |
| 53 |
// exemplar is left in place. AddWithExemplar panics if the value is < 0, if any |
| 54 |
// of the provided labels are invalid, or if the provided labels contain more |
| 55 |
// than 128 runes in total. |
| 56 |
type ExemplarAdder interface { |
| 57 |
AddWithExemplar(value float64, exemplar Labels) |
| 58 |
} |
| 59 |
|
| 60 |
// CounterOpts is an alias for Opts. See there for doc comments. |
| 61 |
type CounterOpts Opts |
| 62 |
|
| 63 |
// CounterVecOpts bundles the options to create a CounterVec metric. |
| 64 |
// It is mandatory to set CounterOpts, see there for mandatory fields. VariableLabels |
| 65 |
// is optional and can safely be left to its default value. |
| 66 |
type CounterVecOpts struct { |
| 67 |
CounterOpts |
| 68 |
|
| 69 |
// VariableLabels are used to partition the metric vector by the given set |
| 70 |
// of labels. Each label value will be constrained with the optional Constraint |
| 71 |
// function, if provided. |
| 72 |
VariableLabels ConstrainableLabels |
| 73 |
} |
| 74 |
|
| 75 |
// NewCounter creates a new Counter based on the provided CounterOpts. |
| 76 |
// |
| 77 |
// The returned implementation also implements ExemplarAdder. It is safe to |
| 78 |
// perform the corresponding type assertion. |
| 79 |
// |
| 80 |
// The returned implementation tracks the counter value in two separate |
| 81 |
// variables, a float64 and a uint64. The latter is used to track calls of the |
| 82 |
// Inc method and calls of the Add method with a value that can be represented |
| 83 |
// as a uint64. This allows atomic increments of the counter with optimal |
| 84 |
// performance. (It is common to have an Inc call in very hot execution paths.) |
| 85 |
// Both internal tracking values are added up in the Write method. This has to |
| 86 |
// be taken into account when it comes to precision and overflow behavior. |
| 87 |
func NewCounter(opts CounterOpts) Counter { |
| 88 |
desc := NewDesc( |
| 89 |
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), |
| 90 |
opts.Help, |
| 91 |
nil, |
| 92 |
opts.ConstLabels, |
| 93 |
) |
| 94 |
if opts.now == nil { |
| 95 |
opts.now = time.Now |
| 96 |
} |
| 97 |
result := &counter{desc: desc, labelPairs: desc.constLabelPairs, now: opts.now} |
| 98 |
result.init(result) // Init self-collection. |
| 99 |
result.createdTs = timestamppb.New(opts.now()) |
| 100 |
return result |
| 101 |
} |
| 102 |
|
| 103 |
type counter struct { |
| 104 |
// valBits contains the bits of the represented float64 value, while |
| 105 |
// valInt stores values that are exact integers. Both have to go first |
| 106 |
// in the struct to guarantee alignment for atomic operations. |
| 107 |
// http://golang.org/pkg/sync/atomic/#pkg-note-BUG |
| 108 |
valBits uint64 |
| 109 |
valInt uint64 |
| 110 |
|
| 111 |
selfCollector |
| 112 |
desc *Desc |
| 113 |
|
| 114 |
createdTs *timestamppb.Timestamp |
| 115 |
labelPairs []*dto.LabelPair |
| 116 |
exemplar atomic.Value // Containing nil or a *dto.Exemplar. |
| 117 |
|
| 118 |
// now is for testing purposes, by default it's time.Now. |
| 119 |
now func() time.Time |
| 120 |
} |
| 121 |
|
| 122 |
func (c *counter) Desc() *Desc { |
| 123 |
return c.desc |
| 124 |
} |
| 125 |
|
| 126 |
func (c *counter) Add(v float64) { |
| 127 |
if v < 0 { |
| 128 |
panic(errors.New("counter cannot decrease in value")) |
| 129 |
} |
| 130 |
|
| 131 |
ival := uint64(v) |
| 132 |
if float64(ival) == v { |
| 133 |
atomic.AddUint64(&c.valInt, ival) |
| 134 |
return |
| 135 |
} |
| 136 |
|
| 137 |
for { |
| 138 |
oldBits := atomic.LoadUint64(&c.valBits) |
| 139 |
newBits := math.Float64bits(math.Float64frombits(oldBits) + v) |
| 140 |
if atomic.CompareAndSwapUint64(&c.valBits, oldBits, newBits) { |
| 141 |
return |
| 142 |
} |
| 143 |
} |
| 144 |
} |
| 145 |
|
| 146 |
func (c *counter) AddWithExemplar(v float64, e Labels) { |
| 147 |
c.Add(v) |
| 148 |
c.updateExemplar(v, e) |
| 149 |
} |
| 150 |
|
| 151 |
func (c *counter) Inc() { |
| 152 |
atomic.AddUint64(&c.valInt, 1) |
| 153 |
} |
| 154 |
|
| 155 |
func (c *counter) get() float64 { |
| 156 |
fval := math.Float64frombits(atomic.LoadUint64(&c.valBits)) |
| 157 |
ival := atomic.LoadUint64(&c.valInt) |
| 158 |
return fval + float64(ival) |
| 159 |
} |
| 160 |
|
| 161 |
func (c *counter) Write(out *dto.Metric) error { |
| 162 |
// Read the Exemplar first and the value second. This is to avoid a race condition |
| 163 |
// where users see an exemplar for a not-yet-existing observation. |
| 164 |
var exemplar *dto.Exemplar |
| 165 |
if e := c.exemplar.Load(); e != nil { |
| 166 |
exemplar = e.(*dto.Exemplar) |
| 167 |
} |
| 168 |
val := c.get() |
| 169 |
return populateMetric(CounterValue, val, c.labelPairs, exemplar, out, c.createdTs) |
| 170 |
} |
| 171 |
|
| 172 |
func (c *counter) updateExemplar(v float64, l Labels) { |
| 173 |
if l == nil { |
| 174 |
return |
| 175 |
} |
| 176 |
e, err := newExemplar(v, c.now(), l) |
| 177 |
if err != nil { |
| 178 |
panic(err) |
| 179 |
} |
| 180 |
c.exemplar.Store(e) |
| 181 |
} |
| 182 |
|
| 183 |
// CounterVec is a Collector that bundles a set of Counters that all share the |
| 184 |
// same Desc, but have different values for their variable labels. This is used |
| 185 |
// if you want to count the same thing partitioned by various dimensions |
| 186 |
// (e.g. number of HTTP requests, partitioned by response code and |
| 187 |
// method). Create instances with NewCounterVec. |
| 188 |
type CounterVec struct { |
| 189 |
*MetricVec |
| 190 |
} |
| 191 |
|
| 192 |
// NewCounterVec creates a new CounterVec based on the provided CounterOpts and |
| 193 |
// partitioned by the given label names. |
| 194 |
func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec { |
| 195 |
return V2.NewCounterVec(CounterVecOpts{ |
| 196 |
CounterOpts: opts, |
| 197 |
VariableLabels: UnconstrainedLabels(labelNames), |
| 198 |
}) |
| 199 |
} |
| 200 |
|
| 201 |
// NewCounterVec creates a new CounterVec based on the provided CounterVecOpts. |
| 202 |
func (v2) NewCounterVec(opts CounterVecOpts) *CounterVec { |
| 203 |
desc := V2.NewDesc( |
| 204 |
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), |
| 205 |
opts.Help, |
| 206 |
opts.VariableLabels, |
| 207 |
opts.ConstLabels, |
| 208 |
) |
| 209 |
if opts.now == nil { |
| 210 |
opts.now = time.Now |
| 211 |
} |
| 212 |
return &CounterVec{ |
| 213 |
MetricVec: NewMetricVec(desc, func(lvs ...string) Metric { |
| 214 |
if len(lvs) != len(desc.variableLabels.names) { |
| 215 |
panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels.names, lvs)) |
| 216 |
} |
| 217 |
result := &counter{desc: desc, labelPairs: MakeLabelPairs(desc, lvs), now: opts.now} |
| 218 |
result.init(result) // Init self-collection. |
| 219 |
result.createdTs = timestamppb.New(opts.now()) |
| 220 |
return result |
| 221 |
}), |
| 222 |
} |
| 223 |
} |
| 224 |
|
| 225 |
// GetMetricWithLabelValues returns the Counter for the given slice of label |
| 226 |
// values (same order as the variable labels in Desc). If that combination of |
| 227 |
// label values is accessed for the first time, a new Counter is created. |
| 228 |
// |
| 229 |
// It is possible to call this method without using the returned Counter to only |
| 230 |
// create the new Counter but leave it at its starting value 0. See also the |
| 231 |
// SummaryVec example. |
| 232 |
// |
| 233 |
// Keeping the Counter for later use is possible (and should be considered if |
| 234 |
// performance is critical), but keep in mind that Reset, DeleteLabelValues and |
| 235 |
// Delete can be used to delete the Counter from the CounterVec. In that case, |
| 236 |
// the Counter will still exist, but it will not be exported anymore, even if a |
| 237 |
// Counter with the same label values is created later. |
| 238 |
// |
| 239 |
// An error is returned if the number of label values is not the same as the |
| 240 |
// number of variable labels in Desc (minus any curried labels). |
| 241 |
// |
| 242 |
// Note that for more than one label value, this method is prone to mistakes |
| 243 |
// caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as |
| 244 |
// an alternative to avoid that type of mistake. For higher label numbers, the |
| 245 |
// latter has a much more readable (albeit more verbose) syntax, but it comes |
| 246 |
// with a performance overhead (for creating and processing the Labels map). |
| 247 |
// See also the GaugeVec example. |
| 248 |
func (v *CounterVec) GetMetricWithLabelValues(lvs ...string) (Counter, error) { |
| 249 |
metric, err := v.MetricVec.GetMetricWithLabelValues(lvs...) |
| 250 |
if metric != nil { |
| 251 |
return metric.(Counter), err |
| 252 |
} |
| 253 |
return nil, err |
| 254 |
} |
| 255 |
|
| 256 |
// GetMetricWith returns the Counter for the given Labels map (the label names |
| 257 |
// must match those of the variable labels in Desc). If that label map is |
| 258 |
// accessed for the first time, a new Counter is created. Implications of |
| 259 |
// creating a Counter without using it and keeping the Counter for later use are |
| 260 |
// the same as for GetMetricWithLabelValues. |
| 261 |
// |
| 262 |
// An error is returned if the number and names of the Labels are inconsistent |
| 263 |
// with those of the variable labels in Desc (minus any curried labels). |
| 264 |
// |
| 265 |
// This method is used for the same purpose as |
| 266 |
// GetMetricWithLabelValues(...string). See there for pros and cons of the two |
| 267 |
// methods. |
| 268 |
func (v *CounterVec) GetMetricWith(labels Labels) (Counter, error) { |
| 269 |
metric, err := v.MetricVec.GetMetricWith(labels) |
| 270 |
if metric != nil { |
| 271 |
return metric.(Counter), err |
| 272 |
} |
| 273 |
return nil, err |
| 274 |
} |
| 275 |
|
| 276 |
// WithLabelValues works as GetMetricWithLabelValues, but panics where |
| 277 |
// GetMetricWithLabelValues would have returned an error. Not returning an |
| 278 |
// error allows shortcuts like |
| 279 |
// |
| 280 |
// myVec.WithLabelValues("404", "GET").Add(42) |
| 281 |
func (v *CounterVec) WithLabelValues(lvs ...string) Counter { |
| 282 |
c, err := v.GetMetricWithLabelValues(lvs...) |
| 283 |
if err != nil { |
| 284 |
panic(err) |
| 285 |
} |
| 286 |
return c |
| 287 |
} |
| 288 |
|
| 289 |
// With works as GetMetricWith, but panics where GetMetricWithLabels would have |
| 290 |
// returned an error. Not returning an error allows shortcuts like |
| 291 |
// |
| 292 |
// myVec.With(prometheus.Labels{"code": "404", "method": "GET"}).Add(42) |
| 293 |
func (v *CounterVec) With(labels Labels) Counter { |
| 294 |
c, err := v.GetMetricWith(labels) |
| 295 |
if err != nil { |
| 296 |
panic(err) |
| 297 |
} |
| 298 |
return c |
| 299 |
} |
| 300 |
|
| 301 |
// CurryWith returns a vector curried with the provided labels, i.e. the |
| 302 |
// returned vector has those labels pre-set for all labeled operations performed |
| 303 |
// on it. The cardinality of the curried vector is reduced accordingly. The |
| 304 |
// order of the remaining labels stays the same (just with the curried labels |
| 305 |
// taken out of the sequence – which is relevant for the |
| 306 |
// (GetMetric)WithLabelValues methods). It is possible to curry a curried |
| 307 |
// vector, but only with labels not yet used for currying before. |
| 308 |
// |
| 309 |
// The metrics contained in the CounterVec are shared between the curried and |
| 310 |
// uncurried vectors. They are just accessed differently. Curried and uncurried |
| 311 |
// vectors behave identically in terms of collection. Only one must be |
| 312 |
// registered with a given registry (usually the uncurried version). The Reset |
| 313 |
// method deletes all metrics, even if called on a curried vector. |
| 314 |
func (v *CounterVec) CurryWith(labels Labels) (*CounterVec, error) { |
| 315 |
vec, err := v.MetricVec.CurryWith(labels) |
| 316 |
if vec != nil { |
| 317 |
return &CounterVec{vec}, err |
| 318 |
} |
| 319 |
return nil, err |
| 320 |
} |
| 321 |
|
| 322 |
// MustCurryWith works as CurryWith but panics where CurryWith would have |
| 323 |
// returned an error. |
| 324 |
func (v *CounterVec) MustCurryWith(labels Labels) *CounterVec { |
| 325 |
vec, err := v.CurryWith(labels) |
| 326 |
if err != nil { |
| 327 |
panic(err) |
| 328 |
} |
| 329 |
return vec |
| 330 |
} |
| 331 |
|
| 332 |
// CounterFunc is a Counter whose value is determined at collect time by calling a |
| 333 |
// provided function. |
| 334 |
// |
| 335 |
// To create CounterFunc instances, use NewCounterFunc. |
| 336 |
type CounterFunc interface { |
| 337 |
Metric |
| 338 |
Collector |
| 339 |
} |
| 340 |
|
| 341 |
// NewCounterFunc creates a new CounterFunc based on the provided |
| 342 |
// CounterOpts. The value reported is determined by calling the given function |
| 343 |
// from within the Write method. Take into account that metric collection may |
| 344 |
// happen concurrently. If that results in concurrent calls to Write, like in |
| 345 |
// the case where a CounterFunc is directly registered with Prometheus, the |
| 346 |
// provided function must be concurrency-safe. The function should also honor |
| 347 |
// the contract for a Counter (values only go up, not down), but compliance will |
| 348 |
// not be checked. |
| 349 |
// |
| 350 |
// Check out the ExampleGaugeFunc examples for the similar GaugeFunc. |
| 351 |
func NewCounterFunc(opts CounterOpts, function func() float64) CounterFunc { |
| 352 |
return newValueFunc(NewDesc( |
| 353 |
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name), |
| 354 |
opts.Help, |
| 355 |
nil, |
| 356 |
opts.ConstLabels, |
| 357 |
), CounterValue, function) |
| 358 |
} |