desc.go 6.5 KB

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