desc.go 6.9 KB

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