value.go 6.6 KB

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