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.
 
 

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