value.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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. "fmt"
  17. "math"
  18. "sort"
  19. "sync/atomic"
  20. dto "github.com/prometheus/client_model/go"
  21. "github.com/golang/protobuf/proto"
  22. )
  23. // ValueType is an enumeration of metric types that represent a simple value.
  24. type ValueType int
  25. // Possible values for the ValueType enum.
  26. const (
  27. _ ValueType = iota
  28. CounterValue
  29. GaugeValue
  30. UntypedValue
  31. )
  32. var errInconsistentCardinality = errors.New("inconsistent label cardinality")
  33. // value is a generic metric for simple values. It implements Metric, Collector,
  34. // Counter, Gauge, and Untyped. Its effective type is determined by
  35. // ValueType. This is a low-level building block used by the library to back the
  36. // implementations of Counter, Gauge, and Untyped.
  37. type value struct {
  38. // valBits containst the bits of the represented float64 value. It has
  39. // to go first in the struct to guarantee alignment for atomic
  40. // operations. http://golang.org/pkg/sync/atomic/#pkg-note-BUG
  41. valBits uint64
  42. selfCollector
  43. desc *Desc
  44. valType ValueType
  45. labelPairs []*dto.LabelPair
  46. }
  47. // newValue returns a newly allocated value with the given Desc, ValueType,
  48. // sample value and label values. It panics if the number of label
  49. // values is different from the number of variable labels in Desc.
  50. func newValue(desc *Desc, valueType ValueType, val float64, labelValues ...string) *value {
  51. if len(labelValues) != len(desc.variableLabels) {
  52. panic(errInconsistentCardinality)
  53. }
  54. result := &value{
  55. desc: desc,
  56. valType: valueType,
  57. valBits: math.Float64bits(val),
  58. labelPairs: makeLabelPairs(desc, labelValues),
  59. }
  60. result.init(result)
  61. return result
  62. }
  63. func (v *value) Desc() *Desc {
  64. return v.desc
  65. }
  66. func (v *value) Set(val float64) {
  67. atomic.StoreUint64(&v.valBits, math.Float64bits(val))
  68. }
  69. func (v *value) Inc() {
  70. v.Add(1)
  71. }
  72. func (v *value) Dec() {
  73. v.Add(-1)
  74. }
  75. func (v *value) Add(val float64) {
  76. for {
  77. oldBits := atomic.LoadUint64(&v.valBits)
  78. newBits := math.Float64bits(math.Float64frombits(oldBits) + val)
  79. if atomic.CompareAndSwapUint64(&v.valBits, oldBits, newBits) {
  80. return
  81. }
  82. }
  83. }
  84. func (v *value) Sub(val float64) {
  85. v.Add(val * -1)
  86. }
  87. func (v *value) Write(out *dto.Metric) error {
  88. val := math.Float64frombits(atomic.LoadUint64(&v.valBits))
  89. return populateMetric(v.valType, val, v.labelPairs, out)
  90. }
  91. // valueFunc is a generic metric for simple values retrieved on collect time
  92. // from a function. It implements Metric and Collector. Its effective type is
  93. // determined by ValueType. This is a low-level building block used by the
  94. // library to back the implementations of CounterFunc, GaugeFunc, and
  95. // UntypedFunc.
  96. type valueFunc struct {
  97. selfCollector
  98. desc *Desc
  99. valType ValueType
  100. function func() float64
  101. labelPairs []*dto.LabelPair
  102. }
  103. // newValueFunc returns a newly allocated valueFunc with the given Desc and
  104. // ValueType. The value reported is determined by calling the given function
  105. // from within the Write method. Take into account that metric collection may
  106. // happen concurrently. If that results in concurrent calls to Write, like in
  107. // the case where a valueFunc is directly registered with Prometheus, the
  108. // provided function must be concurrency-safe.
  109. func newValueFunc(desc *Desc, valueType ValueType, function func() float64) *valueFunc {
  110. result := &valueFunc{
  111. desc: desc,
  112. valType: valueType,
  113. function: function,
  114. labelPairs: makeLabelPairs(desc, nil),
  115. }
  116. result.init(result)
  117. return result
  118. }
  119. func (v *valueFunc) Desc() *Desc {
  120. return v.desc
  121. }
  122. func (v *valueFunc) Write(out *dto.Metric) error {
  123. return populateMetric(v.valType, v.function(), v.labelPairs, out)
  124. }
  125. // NewConstMetric returns a metric with one fixed value that cannot be
  126. // changed. Users of this package will not have much use for it in regular
  127. // operations. However, when implementing custom Collectors, it is useful as a
  128. // throw-away metric that is generated on the fly to send it to Prometheus in
  129. // the Collect method. NewConstMetric returns an error if the length of
  130. // labelValues is not consistent with the variable labels in Desc.
  131. func NewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) (Metric, error) {
  132. if len(desc.variableLabels) != len(labelValues) {
  133. return nil, errInconsistentCardinality
  134. }
  135. return &constMetric{
  136. desc: desc,
  137. valType: valueType,
  138. val: value,
  139. labelPairs: makeLabelPairs(desc, labelValues),
  140. }, nil
  141. }
  142. // MustNewConstMetric is a version of NewConstMetric that panics where
  143. // NewConstMetric would have returned an error.
  144. func MustNewConstMetric(desc *Desc, valueType ValueType, value float64, labelValues ...string) Metric {
  145. m, err := NewConstMetric(desc, valueType, value, labelValues...)
  146. if err != nil {
  147. panic(err)
  148. }
  149. return m
  150. }
  151. type constMetric struct {
  152. desc *Desc
  153. valType ValueType
  154. val float64
  155. labelPairs []*dto.LabelPair
  156. }
  157. func (m *constMetric) Desc() *Desc {
  158. return m.desc
  159. }
  160. func (m *constMetric) Write(out *dto.Metric) error {
  161. return populateMetric(m.valType, m.val, m.labelPairs, out)
  162. }
  163. func populateMetric(
  164. t ValueType,
  165. v float64,
  166. labelPairs []*dto.LabelPair,
  167. m *dto.Metric,
  168. ) error {
  169. m.Label = labelPairs
  170. switch t {
  171. case CounterValue:
  172. m.Counter = &dto.Counter{Value: proto.Float64(v)}
  173. case GaugeValue:
  174. m.Gauge = &dto.Gauge{Value: proto.Float64(v)}
  175. case UntypedValue:
  176. m.Untyped = &dto.Untyped{Value: proto.Float64(v)}
  177. default:
  178. return fmt.Errorf("encountered unknown type %v", t)
  179. }
  180. return nil
  181. }
  182. func makeLabelPairs(desc *Desc, labelValues []string) []*dto.LabelPair {
  183. totalLen := len(desc.variableLabels) + len(desc.constLabelPairs)
  184. if totalLen == 0 {
  185. // Super fast path.
  186. return nil
  187. }
  188. if len(desc.variableLabels) == 0 {
  189. // Moderately fast path.
  190. return desc.constLabelPairs
  191. }
  192. labelPairs := make([]*dto.LabelPair, 0, totalLen)
  193. for i, n := range desc.variableLabels {
  194. labelPairs = append(labelPairs, &dto.LabelPair{
  195. Name: proto.String(n),
  196. Value: proto.String(labelValues[i]),
  197. })
  198. }
  199. for _, lp := range desc.constLabelPairs {
  200. labelPairs = append(labelPairs, lp)
  201. }
  202. sort.Sort(LabelPairSorter(labelPairs))
  203. return labelPairs
  204. }