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.
 
 

200 lines
7.4 KiB

  1. // Copyright 2016 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. "sort"
  17. "strings"
  18. "github.com/prometheus/client_golang/prometheus/internal"
  19. "github.com/cespare/xxhash/v2"
  20. dto "github.com/prometheus/client_model/go"
  21. "github.com/prometheus/common/model"
  22. "google.golang.org/protobuf/proto"
  23. )
  24. // Desc is the descriptor used by every Prometheus Metric. It is essentially
  25. // the immutable meta-data of a Metric. The normal Metric implementations
  26. // included in this package manage their Desc under the hood. Users only have to
  27. // deal with Desc if they use advanced features like the ExpvarCollector or
  28. // custom Collectors and Metrics.
  29. //
  30. // Descriptors registered with the same registry have to fulfill certain
  31. // consistency and uniqueness criteria if they share the same fully-qualified
  32. // name: They must have the same help string and the same label names (aka label
  33. // dimensions) in each, constLabels and variableLabels, but they must differ in
  34. // the values of the constLabels.
  35. //
  36. // Descriptors that share the same fully-qualified names and the same label
  37. // values of their constLabels are considered equal.
  38. //
  39. // Use NewDesc to create new Desc instances.
  40. type Desc struct {
  41. // fqName has been built from Namespace, Subsystem, and Name.
  42. fqName string
  43. // help provides some helpful information about this metric.
  44. help string
  45. // constLabelPairs contains precalculated DTO label pairs based on
  46. // the constant labels.
  47. constLabelPairs []*dto.LabelPair
  48. // variableLabels contains names of labels and normalization function for
  49. // which the metric maintains variable values.
  50. variableLabels ConstrainedLabels
  51. // id is a hash of the values of the ConstLabels and fqName. This
  52. // must be unique among all registered descriptors and can therefore be
  53. // used as an identifier of the descriptor.
  54. id uint64
  55. // dimHash is a hash of the label names (preset and variable) and the
  56. // Help string. Each Desc with the same fqName must have the same
  57. // dimHash.
  58. dimHash uint64
  59. // err is an error that occurred during construction. It is reported on
  60. // registration time.
  61. err error
  62. }
  63. // NewDesc allocates and initializes a new Desc. Errors are recorded in the Desc
  64. // and will be reported on registration time. variableLabels and constLabels can
  65. // be nil if no such labels should be set. fqName must not be empty.
  66. //
  67. // variableLabels only contain the label names. Their label values are variable
  68. // and therefore not part of the Desc. (They are managed within the Metric.)
  69. //
  70. // For constLabels, the label values are constant. Therefore, they are fully
  71. // specified in the Desc. See the Collector example for a usage pattern.
  72. func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) *Desc {
  73. return V2.NewDesc(fqName, help, UnconstrainedLabels(variableLabels), constLabels)
  74. }
  75. // NewDesc allocates and initializes a new Desc. Errors are recorded in the Desc
  76. // and will be reported on registration time. variableLabels and constLabels can
  77. // be nil if no such labels should be set. fqName must not be empty.
  78. //
  79. // variableLabels only contain the label names and normalization functions. Their
  80. // label values are variable and therefore not part of the Desc. (They are managed
  81. // within the Metric.)
  82. //
  83. // For constLabels, the label values are constant. Therefore, they are fully
  84. // specified in the Desc. See the Collector example for a usage pattern.
  85. func (v2) NewDesc(fqName, help string, variableLabels ConstrainableLabels, constLabels Labels) *Desc {
  86. d := &Desc{
  87. fqName: fqName,
  88. help: help,
  89. variableLabels: variableLabels.constrainedLabels(),
  90. }
  91. if !model.IsValidMetricName(model.LabelValue(fqName)) {
  92. d.err = fmt.Errorf("%q is not a valid metric name", fqName)
  93. return d
  94. }
  95. // labelValues contains the label values of const labels (in order of
  96. // their sorted label names) plus the fqName (at position 0).
  97. labelValues := make([]string, 1, len(constLabels)+1)
  98. labelValues[0] = fqName
  99. labelNames := make([]string, 0, len(constLabels)+len(d.variableLabels))
  100. labelNameSet := map[string]struct{}{}
  101. // First add only the const label names and sort them...
  102. for labelName := range constLabels {
  103. if !checkLabelName(labelName) {
  104. d.err = fmt.Errorf("%q is not a valid label name for metric %q", labelName, fqName)
  105. return d
  106. }
  107. labelNames = append(labelNames, labelName)
  108. labelNameSet[labelName] = struct{}{}
  109. }
  110. sort.Strings(labelNames)
  111. // ... so that we can now add const label values in the order of their names.
  112. for _, labelName := range labelNames {
  113. labelValues = append(labelValues, constLabels[labelName])
  114. }
  115. // Validate the const label values. They can't have a wrong cardinality, so
  116. // use in len(labelValues) as expectedNumberOfValues.
  117. if err := validateLabelValues(labelValues, len(labelValues)); err != nil {
  118. d.err = err
  119. return d
  120. }
  121. // Now add the variable label names, but prefix them with something that
  122. // cannot be in a regular label name. That prevents matching the label
  123. // dimension with a different mix between preset and variable labels.
  124. for _, label := range d.variableLabels {
  125. if !checkLabelName(label.Name) {
  126. d.err = fmt.Errorf("%q is not a valid label name for metric %q", label.Name, fqName)
  127. return d
  128. }
  129. labelNames = append(labelNames, "$"+label.Name)
  130. labelNameSet[label.Name] = struct{}{}
  131. }
  132. if len(labelNames) != len(labelNameSet) {
  133. d.err = fmt.Errorf("duplicate label names in constant and variable labels for metric %q", fqName)
  134. return d
  135. }
  136. xxh := xxhash.New()
  137. for _, val := range labelValues {
  138. xxh.WriteString(val)
  139. xxh.Write(separatorByteSlice)
  140. }
  141. d.id = xxh.Sum64()
  142. // Sort labelNames so that order doesn't matter for the hash.
  143. sort.Strings(labelNames)
  144. // Now hash together (in this order) the help string and the sorted
  145. // label names.
  146. xxh.Reset()
  147. xxh.WriteString(help)
  148. xxh.Write(separatorByteSlice)
  149. for _, labelName := range labelNames {
  150. xxh.WriteString(labelName)
  151. xxh.Write(separatorByteSlice)
  152. }
  153. d.dimHash = xxh.Sum64()
  154. d.constLabelPairs = make([]*dto.LabelPair, 0, len(constLabels))
  155. for n, v := range constLabels {
  156. d.constLabelPairs = append(d.constLabelPairs, &dto.LabelPair{
  157. Name: proto.String(n),
  158. Value: proto.String(v),
  159. })
  160. }
  161. sort.Sort(internal.LabelPairSorter(d.constLabelPairs))
  162. return d
  163. }
  164. // NewInvalidDesc returns an invalid descriptor, i.e. a descriptor with the
  165. // provided error set. If a collector returning such a descriptor is registered,
  166. // registration will fail with the provided error. NewInvalidDesc can be used by
  167. // a Collector to signal inability to describe itself.
  168. func NewInvalidDesc(err error) *Desc {
  169. return &Desc{
  170. err: err,
  171. }
  172. }
  173. func (d *Desc) String() string {
  174. lpStrings := make([]string, 0, len(d.constLabelPairs))
  175. for _, lp := range d.constLabelPairs {
  176. lpStrings = append(
  177. lpStrings,
  178. fmt.Sprintf("%s=%q", lp.GetName(), lp.GetValue()),
  179. )
  180. }
  181. return fmt.Sprintf(
  182. "Desc{fqName: %q, help: %q, constLabels: {%s}, variableLabels: %v}",
  183. d.fqName,
  184. d.help,
  185. strings.Join(lpStrings, ","),
  186. d.variableLabels,
  187. )
  188. }