metric.go 6.4 KB

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