counter.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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 128 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) get() float64 {
  118. fval := math.Float64frombits(atomic.LoadUint64(&c.valBits))
  119. ival := atomic.LoadUint64(&c.valInt)
  120. return fval + float64(ival)
  121. }
  122. func (c *counter) Write(out *dto.Metric) error {
  123. // Read the Exemplar first and the value second. This is to avoid a race condition
  124. // where users see an exemplar for a not-yet-existing observation.
  125. var exemplar *dto.Exemplar
  126. if e := c.exemplar.Load(); e != nil {
  127. exemplar = e.(*dto.Exemplar)
  128. }
  129. val := c.get()
  130. return populateMetric(CounterValue, val, c.labelPairs, exemplar, out)
  131. }
  132. func (c *counter) updateExemplar(v float64, l Labels) {
  133. if l == nil {
  134. return
  135. }
  136. e, err := newExemplar(v, c.now(), l)
  137. if err != nil {
  138. panic(err)
  139. }
  140. c.exemplar.Store(e)
  141. }
  142. // CounterVec is a Collector that bundles a set of Counters that all share the
  143. // same Desc, but have different values for their variable labels. This is used
  144. // if you want to count the same thing partitioned by various dimensions
  145. // (e.g. number of HTTP requests, partitioned by response code and
  146. // method). Create instances with NewCounterVec.
  147. type CounterVec struct {
  148. *MetricVec
  149. }
  150. // NewCounterVec creates a new CounterVec based on the provided CounterOpts and
  151. // partitioned by the given label names.
  152. func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec {
  153. desc := NewDesc(
  154. BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
  155. opts.Help,
  156. labelNames,
  157. opts.ConstLabels,
  158. )
  159. return &CounterVec{
  160. MetricVec: NewMetricVec(desc, func(lvs ...string) Metric {
  161. if len(lvs) != len(desc.variableLabels) {
  162. panic(makeInconsistentCardinalityError(desc.fqName, desc.variableLabels, lvs))
  163. }
  164. result := &counter{desc: desc, labelPairs: MakeLabelPairs(desc, lvs), now: time.Now}
  165. result.init(result) // Init self-collection.
  166. return result
  167. }),
  168. }
  169. }
  170. // GetMetricWithLabelValues returns the Counter for the given slice of label
  171. // values (same order as the variable labels in Desc). If that combination of
  172. // label values is accessed for the first time, a new Counter is created.
  173. //
  174. // It is possible to call this method without using the returned Counter to only
  175. // create the new Counter but leave it at its starting value 0. See also the
  176. // SummaryVec example.
  177. //
  178. // Keeping the Counter for later use is possible (and should be considered if
  179. // performance is critical), but keep in mind that Reset, DeleteLabelValues and
  180. // Delete can be used to delete the Counter from the CounterVec. In that case,
  181. // the Counter will still exist, but it will not be exported anymore, even if a
  182. // Counter with the same label values is created later.
  183. //
  184. // An error is returned if the number of label values is not the same as the
  185. // number of variable labels in Desc (minus any curried labels).
  186. //
  187. // Note that for more than one label value, this method is prone to mistakes
  188. // caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as
  189. // an alternative to avoid that type of mistake. For higher label numbers, the
  190. // latter has a much more readable (albeit more verbose) syntax, but it comes
  191. // with a performance overhead (for creating and processing the Labels map).
  192. // See also the GaugeVec example.
  193. func (v *CounterVec) GetMetricWithLabelValues(lvs ...string) (Counter, error) {
  194. metric, err := v.MetricVec.GetMetricWithLabelValues(lvs...)
  195. if metric != nil {
  196. return metric.(Counter), err
  197. }
  198. return nil, err
  199. }
  200. // GetMetricWith returns the Counter for the given Labels map (the label names
  201. // must match those of the variable labels in Desc). If that label map is
  202. // accessed for the first time, a new Counter is created. Implications of
  203. // creating a Counter without using it and keeping the Counter for later use are
  204. // the same as for GetMetricWithLabelValues.
  205. //
  206. // An error is returned if the number and names of the Labels are inconsistent
  207. // with those of the variable labels in Desc (minus any curried labels).
  208. //
  209. // This method is used for the same purpose as
  210. // GetMetricWithLabelValues(...string). See there for pros and cons of the two
  211. // methods.
  212. func (v *CounterVec) GetMetricWith(labels Labels) (Counter, error) {
  213. metric, err := v.MetricVec.GetMetricWith(labels)
  214. if metric != nil {
  215. return metric.(Counter), err
  216. }
  217. return nil, err
  218. }
  219. // WithLabelValues works as GetMetricWithLabelValues, but panics where
  220. // GetMetricWithLabelValues would have returned an error. Not returning an
  221. // error allows shortcuts like
  222. // myVec.WithLabelValues("404", "GET").Add(42)
  223. func (v *CounterVec) WithLabelValues(lvs ...string) Counter {
  224. c, err := v.GetMetricWithLabelValues(lvs...)
  225. if err != nil {
  226. panic(err)
  227. }
  228. return c
  229. }
  230. // With works as GetMetricWith, but panics where GetMetricWithLabels would have
  231. // returned an error. Not returning an error allows shortcuts like
  232. // myVec.With(prometheus.Labels{"code": "404", "method": "GET"}).Add(42)
  233. func (v *CounterVec) With(labels Labels) Counter {
  234. c, err := v.GetMetricWith(labels)
  235. if err != nil {
  236. panic(err)
  237. }
  238. return c
  239. }
  240. // CurryWith returns a vector curried with the provided labels, i.e. the
  241. // returned vector has those labels pre-set for all labeled operations performed
  242. // on it. The cardinality of the curried vector is reduced accordingly. The
  243. // order of the remaining labels stays the same (just with the curried labels
  244. // taken out of the sequence – which is relevant for the
  245. // (GetMetric)WithLabelValues methods). It is possible to curry a curried
  246. // vector, but only with labels not yet used for currying before.
  247. //
  248. // The metrics contained in the CounterVec are shared between the curried and
  249. // uncurried vectors. They are just accessed differently. Curried and uncurried
  250. // vectors behave identically in terms of collection. Only one must be
  251. // registered with a given registry (usually the uncurried version). The Reset
  252. // method deletes all metrics, even if called on a curried vector.
  253. func (v *CounterVec) CurryWith(labels Labels) (*CounterVec, error) {
  254. vec, err := v.MetricVec.CurryWith(labels)
  255. if vec != nil {
  256. return &CounterVec{vec}, err
  257. }
  258. return nil, err
  259. }
  260. // MustCurryWith works as CurryWith but panics where CurryWith would have
  261. // returned an error.
  262. func (v *CounterVec) MustCurryWith(labels Labels) *CounterVec {
  263. vec, err := v.CurryWith(labels)
  264. if err != nil {
  265. panic(err)
  266. }
  267. return vec
  268. }
  269. // CounterFunc is a Counter whose value is determined at collect time by calling a
  270. // provided function.
  271. //
  272. // To create CounterFunc instances, use NewCounterFunc.
  273. type CounterFunc interface {
  274. Metric
  275. Collector
  276. }
  277. // NewCounterFunc creates a new CounterFunc based on the provided
  278. // CounterOpts. The value reported is determined by calling the given function
  279. // from within the Write method. Take into account that metric collection may
  280. // happen concurrently. If that results in concurrent calls to Write, like in
  281. // the case where a CounterFunc is directly registered with Prometheus, the
  282. // provided function must be concurrency-safe. The function should also honor
  283. // the contract for a Counter (values only go up, not down), but compliance will
  284. // not be checked.
  285. //
  286. // Check out the ExampleGaugeFunc examples for the similar GaugeFunc.
  287. func NewCounterFunc(opts CounterOpts, function func() float64) CounterFunc {
  288. return newValueFunc(NewDesc(
  289. BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
  290. opts.Help,
  291. nil,
  292. opts.ConstLabels,
  293. ), CounterValue, function)
  294. }