vec.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. "bytes"
  16. "fmt"
  17. "hash"
  18. "sync"
  19. )
  20. // MetricVec is a Collector to bundle metrics of the same name that
  21. // differ in their label values. MetricVec is usually not used directly but as a
  22. // building block for implementations of vectors of a given metric
  23. // type. GaugeVec, CounterVec, SummaryVec, and UntypedVec are examples already
  24. // provided in this package.
  25. type MetricVec struct {
  26. mtx sync.RWMutex // Protects not only children, but also hash and buf.
  27. children map[uint64]Metric
  28. desc *Desc
  29. // hash is our own hash instance to avoid repeated allocations.
  30. hash hash.Hash64
  31. // buf is used to copy string contents into it for hashing,
  32. // again to avoid allocations.
  33. buf bytes.Buffer
  34. newMetric func(labelValues ...string) Metric
  35. }
  36. // Describe implements Collector. The length of the returned slice
  37. // is always one.
  38. func (m *MetricVec) Describe(ch chan<- *Desc) {
  39. ch <- m.desc
  40. }
  41. // Collect implements Collector.
  42. func (m *MetricVec) Collect(ch chan<- Metric) {
  43. m.mtx.RLock()
  44. defer m.mtx.RUnlock()
  45. for _, metric := range m.children {
  46. ch <- metric
  47. }
  48. }
  49. // GetMetricWithLabelValues returns the Metric for the given slice of label
  50. // values (same order as the VariableLabels in Desc). If that combination of
  51. // label values is accessed for the first time, a new Metric is created.
  52. //
  53. // It is possible to call this method without using the returned Metric to only
  54. // create the new Metric but leave it at its start value (e.g. a Summary or
  55. // Histogram without any observations). See also the SummaryVec example.
  56. //
  57. // Keeping the Metric for later use is possible (and should be considered if
  58. // performance is critical), but keep in mind that Reset, DeleteLabelValues and
  59. // Delete can be used to delete the Metric from the MetricVec. In that case, the
  60. // Metric will still exist, but it will not be exported anymore, even if a
  61. // Metric with the same label values is created later. See also the CounterVec
  62. // example.
  63. //
  64. // An error is returned if the number of label values is not the same as the
  65. // number of VariableLabels in Desc.
  66. //
  67. // Note that for more than one label value, this method is prone to mistakes
  68. // caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as
  69. // an alternative to avoid that type of mistake. For higher label numbers, the
  70. // latter has a much more readable (albeit more verbose) syntax, but it comes
  71. // with a performance overhead (for creating and processing the Labels map).
  72. // See also the GaugeVec example.
  73. func (m *MetricVec) GetMetricWithLabelValues(lvs ...string) (Metric, error) {
  74. m.mtx.Lock()
  75. defer m.mtx.Unlock()
  76. h, err := m.hashLabelValues(lvs)
  77. if err != nil {
  78. return nil, err
  79. }
  80. return m.getOrCreateMetric(h, lvs...), nil
  81. }
  82. // GetMetricWith returns the Metric for the given Labels map (the label names
  83. // must match those of the VariableLabels in Desc). If that label map is
  84. // accessed for the first time, a new Metric is created. Implications of
  85. // creating a Metric without using it and keeping the Metric for later use are
  86. // the same as for GetMetricWithLabelValues.
  87. //
  88. // An error is returned if the number and names of the Labels are inconsistent
  89. // with those of the VariableLabels in Desc.
  90. //
  91. // This method is used for the same purpose as
  92. // GetMetricWithLabelValues(...string). See there for pros and cons of the two
  93. // methods.
  94. func (m *MetricVec) GetMetricWith(labels Labels) (Metric, error) {
  95. m.mtx.Lock()
  96. defer m.mtx.Unlock()
  97. h, err := m.hashLabels(labels)
  98. if err != nil {
  99. return nil, err
  100. }
  101. lvs := make([]string, len(labels))
  102. for i, label := range m.desc.variableLabels {
  103. lvs[i] = labels[label]
  104. }
  105. return m.getOrCreateMetric(h, lvs...), nil
  106. }
  107. // WithLabelValues works as GetMetricWithLabelValues, but panics if an error
  108. // occurs. The method allows neat syntax like:
  109. // httpReqs.WithLabelValues("404", "POST").Inc()
  110. func (m *MetricVec) WithLabelValues(lvs ...string) Metric {
  111. metric, err := m.GetMetricWithLabelValues(lvs...)
  112. if err != nil {
  113. panic(err)
  114. }
  115. return metric
  116. }
  117. // With works as GetMetricWith, but panics if an error occurs. The method allows
  118. // neat syntax like:
  119. // httpReqs.With(Labels{"status":"404", "method":"POST"}).Inc()
  120. func (m *MetricVec) With(labels Labels) Metric {
  121. metric, err := m.GetMetricWith(labels)
  122. if err != nil {
  123. panic(err)
  124. }
  125. return metric
  126. }
  127. // DeleteLabelValues removes the metric where the variable labels are the same
  128. // as those passed in as labels (same order as the VariableLabels in Desc). It
  129. // returns true if a metric was deleted.
  130. //
  131. // It is not an error if the number of label values is not the same as the
  132. // number of VariableLabels in Desc. However, such inconsistent label count can
  133. // never match an actual Metric, so the method will always return false in that
  134. // case.
  135. //
  136. // Note that for more than one label value, this method is prone to mistakes
  137. // caused by an incorrect order of arguments. Consider Delete(Labels) as an
  138. // alternative to avoid that type of mistake. For higher label numbers, the
  139. // latter has a much more readable (albeit more verbose) syntax, but it comes
  140. // with a performance overhead (for creating and processing the Labels map).
  141. // See also the CounterVec example.
  142. func (m *MetricVec) DeleteLabelValues(lvs ...string) bool {
  143. m.mtx.Lock()
  144. defer m.mtx.Unlock()
  145. h, err := m.hashLabelValues(lvs)
  146. if err != nil {
  147. return false
  148. }
  149. if _, has := m.children[h]; !has {
  150. return false
  151. }
  152. delete(m.children, h)
  153. return true
  154. }
  155. // Delete deletes the metric where the variable labels are the same as those
  156. // passed in as labels. It returns true if a metric was deleted.
  157. //
  158. // It is not an error if the number and names of the Labels are inconsistent
  159. // with those of the VariableLabels in the Desc of the MetricVec. However, such
  160. // inconsistent Labels can never match an actual Metric, so the method will
  161. // always return false in that case.
  162. //
  163. // This method is used for the same purpose as DeleteLabelValues(...string). See
  164. // there for pros and cons of the two methods.
  165. func (m *MetricVec) Delete(labels Labels) bool {
  166. m.mtx.Lock()
  167. defer m.mtx.Unlock()
  168. h, err := m.hashLabels(labels)
  169. if err != nil {
  170. return false
  171. }
  172. if _, has := m.children[h]; !has {
  173. return false
  174. }
  175. delete(m.children, h)
  176. return true
  177. }
  178. // Reset deletes all metrics in this vector.
  179. func (m *MetricVec) Reset() {
  180. m.mtx.Lock()
  181. defer m.mtx.Unlock()
  182. for h := range m.children {
  183. delete(m.children, h)
  184. }
  185. }
  186. func (m *MetricVec) hashLabelValues(vals []string) (uint64, error) {
  187. if len(vals) != len(m.desc.variableLabels) {
  188. return 0, errInconsistentCardinality
  189. }
  190. m.hash.Reset()
  191. for _, val := range vals {
  192. m.buf.Reset()
  193. m.buf.WriteString(val)
  194. m.hash.Write(m.buf.Bytes())
  195. }
  196. return m.hash.Sum64(), nil
  197. }
  198. func (m *MetricVec) hashLabels(labels Labels) (uint64, error) {
  199. if len(labels) != len(m.desc.variableLabels) {
  200. return 0, errInconsistentCardinality
  201. }
  202. m.hash.Reset()
  203. for _, label := range m.desc.variableLabels {
  204. val, ok := labels[label]
  205. if !ok {
  206. return 0, fmt.Errorf("label name %q missing in label map", label)
  207. }
  208. m.buf.Reset()
  209. m.buf.WriteString(val)
  210. m.hash.Write(m.buf.Bytes())
  211. }
  212. return m.hash.Sum64(), nil
  213. }
  214. func (m *MetricVec) getOrCreateMetric(hash uint64, labelValues ...string) Metric {
  215. metric, ok := m.children[hash]
  216. if !ok {
  217. // Copy labelValues. Otherwise, they would be allocated even if we don't go
  218. // down this code path.
  219. copiedLabelValues := append(make([]string, 0, len(labelValues)), labelValues...)
  220. metric = m.newMetric(copiedLabelValues...)
  221. m.children[hash] = metric
  222. }
  223. return metric
  224. }