You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

counter.go 13KB

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