metric.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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 and Help to a non-empty string. All other fields
  56. // are optional and can safely be left at their zero value.
  57. type Opts struct {
  58. // Namespace, Subsystem, and Name are components of the fully-qualified
  59. // name of the Metric (created by joining these components with
  60. // "_"). Only Name is mandatory, the others merely help structuring the
  61. // name. Note that the fully-qualified name of the metric must be a
  62. // valid Prometheus metric name.
  63. Namespace string
  64. Subsystem string
  65. Name string
  66. // Help provides information about this metric. Mandatory!
  67. //
  68. // Metrics with the same fully-qualified name must have the same Help
  69. // string.
  70. Help string
  71. // ConstLabels are used to attach fixed labels to this metric. Metrics
  72. // with the same fully-qualified name must have the same label names in
  73. // their ConstLabels.
  74. //
  75. // ConstLabels are only used rarely. In particular, do not use them to
  76. // attach the same labels to all your metrics. Those use cases are
  77. // better covered by target labels set by the scraping Prometheus
  78. // server, or by one specific metric (e.g. a build_info or a
  79. // machine_role metric). See also
  80. // https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels,-not-static-scraped-labels
  81. ConstLabels Labels
  82. }
  83. // BuildFQName joins the given three name components by "_". Empty name
  84. // components are ignored. If the name parameter itself is empty, an empty
  85. // string is returned, no matter what. Metric implementations included in this
  86. // library use this function internally to generate the fully-qualified metric
  87. // name from the name component in their Opts. Users of the library will only
  88. // need this function if they implement their own Metric or instantiate a Desc
  89. // (with NewDesc) directly.
  90. func BuildFQName(namespace, subsystem, name string) string {
  91. if name == "" {
  92. return ""
  93. }
  94. switch {
  95. case namespace != "" && subsystem != "":
  96. return strings.Join([]string{namespace, subsystem, name}, "_")
  97. case namespace != "":
  98. return strings.Join([]string{namespace, name}, "_")
  99. case subsystem != "":
  100. return strings.Join([]string{subsystem, name}, "_")
  101. }
  102. return name
  103. }
  104. // labelPairSorter implements sort.Interface. It is used to sort a slice of
  105. // dto.LabelPair pointers.
  106. type labelPairSorter []*dto.LabelPair
  107. func (s labelPairSorter) Len() int {
  108. return len(s)
  109. }
  110. func (s labelPairSorter) Swap(i, j int) {
  111. s[i], s[j] = s[j], s[i]
  112. }
  113. func (s labelPairSorter) Less(i, j int) bool {
  114. return s[i].GetName() < s[j].GetName()
  115. }
  116. type invalidMetric struct {
  117. desc *Desc
  118. err error
  119. }
  120. // NewInvalidMetric returns a metric whose Write method always returns the
  121. // provided error. It is useful if a Collector finds itself unable to collect
  122. // a metric and wishes to report an error to the registry.
  123. func NewInvalidMetric(desc *Desc, err error) Metric {
  124. return &invalidMetric{desc, err}
  125. }
  126. func (m *invalidMetric) Desc() *Desc { return m.desc }
  127. func (m *invalidMetric) Write(*dto.Metric) error { return m.err }
  128. type timestampedMetric struct {
  129. Metric
  130. t time.Time
  131. }
  132. func (m timestampedMetric) Write(pb *dto.Metric) error {
  133. e := m.Metric.Write(pb)
  134. pb.TimestampMs = proto.Int64(m.t.Unix()*1000 + int64(m.t.Nanosecond()/1000000))
  135. return e
  136. }
  137. // NewMetricWithTimestamp returns a new Metric wrapping the provided Metric in a
  138. // way that it has an explicit timestamp set to the provided Time. This is only
  139. // useful in rare cases as the timestamp of a Prometheus metric should usually
  140. // be set by the Prometheus server during scraping. Exceptions include mirroring
  141. // metrics with given timestamps from other metric
  142. // sources.
  143. //
  144. // NewMetricWithTimestamp works best with MustNewConstMetric,
  145. // MustNewConstHistogram, and MustNewConstSummary, see example.
  146. //
  147. // Currently, the exposition formats used by Prometheus are limited to
  148. // millisecond resolution. Thus, the provided time will be rounded down to the
  149. // next full millisecond value.
  150. func NewMetricWithTimestamp(t time.Time, m Metric) Metric {
  151. return timestampedMetric{Metric: m, t: t}
  152. }