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.

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