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.
 
 

326 line
11 KiB

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