metric.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. // Copyright 2014 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. "strings"
  16. "time"
  17. //lint:ignore SA1019 Need to keep deprecated package for compatibility.
  18. "github.com/golang/protobuf/proto"
  19. "github.com/prometheus/common/model"
  20. dto "github.com/prometheus/client_model/go"
  21. )
  22. var separatorByteSlice = []byte{model.SeparatorByte} // For convenient use with xxhash.
  23. // A Metric models a single sample value with its meta data being exported to
  24. // Prometheus. Implementations of Metric in this package are Gauge, Counter,
  25. // Histogram, Summary, and Untyped.
  26. type Metric interface {
  27. // Desc returns the descriptor for the Metric. This method idempotently
  28. // returns the same descriptor throughout the lifetime of the
  29. // Metric. The returned descriptor is immutable by contract. A Metric
  30. // unable to describe itself must return an invalid descriptor (created
  31. // with NewInvalidDesc).
  32. Desc() *Desc
  33. // Write encodes the Metric into a "Metric" Protocol Buffer data
  34. // transmission object.
  35. //
  36. // Metric implementations must observe concurrency safety as reads of
  37. // this metric may occur at any time, and any blocking occurs at the
  38. // expense of total performance of rendering all registered
  39. // metrics. Ideally, Metric implementations should support concurrent
  40. // readers.
  41. //
  42. // While populating dto.Metric, it is the responsibility of the
  43. // implementation to ensure validity of the Metric protobuf (like valid
  44. // UTF-8 strings or syntactically valid metric and label names). It is
  45. // recommended to sort labels lexicographically. Callers of Write should
  46. // still make sure of sorting if they depend on it.
  47. Write(*dto.Metric) error
  48. // TODO(beorn7): The original rationale of passing in a pre-allocated
  49. // dto.Metric protobuf to save allocations has disappeared. The
  50. // signature of this method should be changed to "Write() (*dto.Metric,
  51. // error)".
  52. }
  53. // Opts bundles the options for creating most Metric types. Each metric
  54. // implementation XXX has its own XXXOpts type, but in most cases, it is just be
  55. // an alias of this type (which might change when the requirement arises.)
  56. //
  57. // It is mandatory to set Name to a non-empty string. All other fields are
  58. // optional and can safely be left at their zero value, although it is strongly
  59. // encouraged to set a Help string.
  60. type Opts struct {
  61. // Namespace, Subsystem, and Name are components of the fully-qualified
  62. // name of the Metric (created by joining these components with
  63. // "_"). Only Name is mandatory, the others merely help structuring the
  64. // name. Note that the fully-qualified name of the metric must be a
  65. // valid Prometheus metric name.
  66. Namespace string
  67. Subsystem string
  68. Name string
  69. // Help provides information about this metric.
  70. //
  71. // Metrics with the same fully-qualified name must have the same Help
  72. // string.
  73. Help string
  74. // ConstLabels are used to attach fixed labels to this metric. Metrics
  75. // with the same fully-qualified name must have the same label names in
  76. // their ConstLabels.
  77. //
  78. // ConstLabels are only used rarely. In particular, do not use them to
  79. // attach the same labels to all your metrics. Those use cases are
  80. // better covered by target labels set by the scraping Prometheus
  81. // server, or by one specific metric (e.g. a build_info or a
  82. // machine_role metric). See also
  83. // https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels,-not-static-scraped-labels
  84. ConstLabels Labels
  85. }
  86. // BuildFQName joins the given three name components by "_". Empty name
  87. // components are ignored. If the name parameter itself is empty, an empty
  88. // string is returned, no matter what. Metric implementations included in this
  89. // library use this function internally to generate the fully-qualified metric
  90. // name from the name component in their Opts. Users of the library will only
  91. // need this function if they implement their own Metric or instantiate a Desc
  92. // (with NewDesc) directly.
  93. func BuildFQName(namespace, subsystem, name string) string {
  94. if name == "" {
  95. return ""
  96. }
  97. switch {
  98. case namespace != "" && subsystem != "":
  99. return strings.Join([]string{namespace, subsystem, name}, "_")
  100. case namespace != "":
  101. return strings.Join([]string{namespace, name}, "_")
  102. case subsystem != "":
  103. return strings.Join([]string{subsystem, name}, "_")
  104. }
  105. return name
  106. }
  107. // labelPairSorter implements sort.Interface. It is used to sort a slice of
  108. // dto.LabelPair pointers.
  109. type labelPairSorter []*dto.LabelPair
  110. func (s labelPairSorter) Len() int {
  111. return len(s)
  112. }
  113. func (s labelPairSorter) Swap(i, j int) {
  114. s[i], s[j] = s[j], s[i]
  115. }
  116. func (s labelPairSorter) Less(i, j int) bool {
  117. return s[i].GetName() < s[j].GetName()
  118. }
  119. type invalidMetric struct {
  120. desc *Desc
  121. err error
  122. }
  123. // NewInvalidMetric returns a metric whose Write method always returns the
  124. // provided error. It is useful if a Collector finds itself unable to collect
  125. // a metric and wishes to report an error to the registry.
  126. func NewInvalidMetric(desc *Desc, err error) Metric {
  127. return &invalidMetric{desc, err}
  128. }
  129. func (m *invalidMetric) Desc() *Desc { return m.desc }
  130. func (m *invalidMetric) Write(*dto.Metric) error { return m.err }
  131. type timestampedMetric struct {
  132. Metric
  133. t time.Time
  134. }
  135. func (m timestampedMetric) Write(pb *dto.Metric) error {
  136. e := m.Metric.Write(pb)
  137. pb.TimestampMs = proto.Int64(m.t.Unix()*1000 + int64(m.t.Nanosecond()/1000000))
  138. return e
  139. }
  140. // NewMetricWithTimestamp returns a new Metric wrapping the provided Metric in a
  141. // way that it has an explicit timestamp set to the provided Time. This is only
  142. // useful in rare cases as the timestamp of a Prometheus metric should usually
  143. // be set by the Prometheus server during scraping. Exceptions include mirroring
  144. // metrics with given timestamps from other metric
  145. // sources.
  146. //
  147. // NewMetricWithTimestamp works best with MustNewConstMetric,
  148. // MustNewConstHistogram, and MustNewConstSummary, see example.
  149. //
  150. // Currently, the exposition formats used by Prometheus are limited to
  151. // millisecond resolution. Thus, the provided time will be rounded down to the
  152. // next full millisecond value.
  153. func NewMetricWithTimestamp(t time.Time, m Metric) Metric {
  154. return timestampedMetric{Metric: m, t: t}
  155. }