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.

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