counter.go 11 KB

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