You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

metric.go 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. "errors"
  16. "math"
  17. "sort"
  18. "strings"
  19. "time"
  20. dto "github.com/prometheus/client_model/go"
  21. "github.com/prometheus/common/model"
  22. "google.golang.org/protobuf/proto"
  23. )
  24. var separatorByteSlice = []byte{model.SeparatorByte} // For convenient use with xxhash.
  25. // A Metric models a single sample value with its meta data being exported to
  26. // Prometheus. Implementations of Metric in this package are Gauge, Counter,
  27. // Histogram, Summary, and Untyped.
  28. type Metric interface {
  29. // Desc returns the descriptor for the Metric. This method idempotently
  30. // returns the same descriptor throughout the lifetime of the
  31. // Metric. The returned descriptor is immutable by contract. A Metric
  32. // unable to describe itself must return an invalid descriptor (created
  33. // with NewInvalidDesc).
  34. Desc() *Desc
  35. // Write encodes the Metric into a "Metric" Protocol Buffer data
  36. // transmission object.
  37. //
  38. // Metric implementations must observe concurrency safety as reads of
  39. // this metric may occur at any time, and any blocking occurs at the
  40. // expense of total performance of rendering all registered
  41. // metrics. Ideally, Metric implementations should support concurrent
  42. // readers.
  43. //
  44. // While populating dto.Metric, it is the responsibility of the
  45. // implementation to ensure validity of the Metric protobuf (like valid
  46. // UTF-8 strings or syntactically valid metric and label names). It is
  47. // recommended to sort labels lexicographically. Callers of Write should
  48. // still make sure of sorting if they depend on it.
  49. Write(*dto.Metric) error
  50. // TODO(beorn7): The original rationale of passing in a pre-allocated
  51. // dto.Metric protobuf to save allocations has disappeared. The
  52. // signature of this method should be changed to "Write() (*dto.Metric,
  53. // error)".
  54. }
  55. // Opts bundles the options for creating most Metric types. Each metric
  56. // implementation XXX has its own XXXOpts type, but in most cases, it is just
  57. // an alias of this type (which might change when the requirement arises.)
  58. //
  59. // It is mandatory to set Name to a non-empty string. All other fields are
  60. // optional and can safely be left at their zero value, although it is strongly
  61. // encouraged to set a Help string.
  62. type Opts struct {
  63. // Namespace, Subsystem, and Name are components of the fully-qualified
  64. // name of the Metric (created by joining these components with
  65. // "_"). Only Name is mandatory, the others merely help structuring the
  66. // name. Note that the fully-qualified name of the metric must be a
  67. // valid Prometheus metric name.
  68. Namespace string
  69. Subsystem string
  70. Name string
  71. // Help provides information about this metric.
  72. //
  73. // Metrics with the same fully-qualified name must have the same Help
  74. // string.
  75. Help string
  76. // ConstLabels are used to attach fixed labels to this metric. Metrics
  77. // with the same fully-qualified name must have the same label names in
  78. // their ConstLabels.
  79. //
  80. // ConstLabels are only used rarely. In particular, do not use them to
  81. // attach the same labels to all your metrics. Those use cases are
  82. // better covered by target labels set by the scraping Prometheus
  83. // server, or by one specific metric (e.g. a build_info or a
  84. // machine_role metric). See also
  85. // https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels-not-static-scraped-labels
  86. ConstLabels Labels
  87. // now is for testing purposes, by default it's time.Now.
  88. now func() time.Time
  89. }
  90. // BuildFQName joins the given three name components by "_". Empty name
  91. // components are ignored. If the name parameter itself is empty, an empty
  92. // string is returned, no matter what. Metric implementations included in this
  93. // library use this function internally to generate the fully-qualified metric
  94. // name from the name component in their Opts. Users of the library will only
  95. // need this function if they implement their own Metric or instantiate a Desc
  96. // (with NewDesc) directly.
  97. func BuildFQName(namespace, subsystem, name string) string {
  98. if name == "" {
  99. return ""
  100. }
  101. switch {
  102. case namespace != "" && subsystem != "":
  103. return strings.Join([]string{namespace, subsystem, name}, "_")
  104. case namespace != "":
  105. return strings.Join([]string{namespace, name}, "_")
  106. case subsystem != "":
  107. return strings.Join([]string{subsystem, name}, "_")
  108. }
  109. return name
  110. }
  111. type invalidMetric struct {
  112. desc *Desc
  113. err error
  114. }
  115. // NewInvalidMetric returns a metric whose Write method always returns the
  116. // provided error. It is useful if a Collector finds itself unable to collect
  117. // a metric and wishes to report an error to the registry.
  118. func NewInvalidMetric(desc *Desc, err error) Metric {
  119. return &invalidMetric{desc, err}
  120. }
  121. func (m *invalidMetric) Desc() *Desc { return m.desc }
  122. func (m *invalidMetric) Write(*dto.Metric) error { return m.err }
  123. type timestampedMetric struct {
  124. Metric
  125. t time.Time
  126. }
  127. func (m timestampedMetric) Write(pb *dto.Metric) error {
  128. e := m.Metric.Write(pb)
  129. pb.TimestampMs = proto.Int64(m.t.Unix()*1000 + int64(m.t.Nanosecond()/1000000))
  130. return e
  131. }
  132. // NewMetricWithTimestamp returns a new Metric wrapping the provided Metric in a
  133. // way that it has an explicit timestamp set to the provided Time. This is only
  134. // useful in rare cases as the timestamp of a Prometheus metric should usually
  135. // be set by the Prometheus server during scraping. Exceptions include mirroring
  136. // metrics with given timestamps from other metric
  137. // sources.
  138. //
  139. // NewMetricWithTimestamp works best with MustNewConstMetric,
  140. // MustNewConstHistogram, and MustNewConstSummary, see example.
  141. //
  142. // Currently, the exposition formats used by Prometheus are limited to
  143. // millisecond resolution. Thus, the provided time will be rounded down to the
  144. // next full millisecond value.
  145. func NewMetricWithTimestamp(t time.Time, m Metric) Metric {
  146. return timestampedMetric{Metric: m, t: t}
  147. }
  148. type withExemplarsMetric struct {
  149. Metric
  150. exemplars []*dto.Exemplar
  151. }
  152. func (m *withExemplarsMetric) Write(pb *dto.Metric) error {
  153. if err := m.Metric.Write(pb); err != nil {
  154. return err
  155. }
  156. switch {
  157. case pb.Counter != nil:
  158. pb.Counter.Exemplar = m.exemplars[len(m.exemplars)-1]
  159. case pb.Histogram != nil:
  160. for _, e := range m.exemplars {
  161. // pb.Histogram.Bucket are sorted by UpperBound.
  162. i := sort.Search(len(pb.Histogram.Bucket), func(i int) bool {
  163. return pb.Histogram.Bucket[i].GetUpperBound() >= e.GetValue()
  164. })
  165. if i < len(pb.Histogram.Bucket) {
  166. pb.Histogram.Bucket[i].Exemplar = e
  167. } else {
  168. // The +Inf bucket should be explicitly added if there is an exemplar for it, similar to non-const histogram logic in https://github.com/prometheus/client_golang/blob/main/prometheus/histogram.go#L357-L365.
  169. b := &dto.Bucket{
  170. CumulativeCount: proto.Uint64(pb.Histogram.GetSampleCount()),
  171. UpperBound: proto.Float64(math.Inf(1)),
  172. Exemplar: e,
  173. }
  174. pb.Histogram.Bucket = append(pb.Histogram.Bucket, b)
  175. }
  176. }
  177. default:
  178. // TODO(bwplotka): Implement Gauge?
  179. return errors.New("cannot inject exemplar into Gauge, Summary or Untyped")
  180. }
  181. return nil
  182. }
  183. // Exemplar is easier to use, user-facing representation of *dto.Exemplar.
  184. type Exemplar struct {
  185. Value float64
  186. Labels Labels
  187. // Optional.
  188. // Default value (time.Time{}) indicates its empty, which should be
  189. // understood as time.Now() time at the moment of creation of metric.
  190. Timestamp time.Time
  191. }
  192. // NewMetricWithExemplars returns a new Metric wrapping the provided Metric with given
  193. // exemplars. Exemplars are validated.
  194. //
  195. // Only last applicable exemplar is injected from the list.
  196. // For example for Counter it means last exemplar is injected.
  197. // For Histogram, it means last applicable exemplar for each bucket is injected.
  198. //
  199. // NewMetricWithExemplars works best with MustNewConstMetric and
  200. // MustNewConstHistogram, see example.
  201. func NewMetricWithExemplars(m Metric, exemplars ...Exemplar) (Metric, error) {
  202. if len(exemplars) == 0 {
  203. return nil, errors.New("no exemplar was passed for NewMetricWithExemplars")
  204. }
  205. var (
  206. now = time.Now()
  207. exs = make([]*dto.Exemplar, len(exemplars))
  208. err error
  209. )
  210. for i, e := range exemplars {
  211. ts := e.Timestamp
  212. if ts == (time.Time{}) {
  213. ts = now
  214. }
  215. exs[i], err = newExemplar(e.Value, ts, e.Labels)
  216. if err != nil {
  217. return nil, err
  218. }
  219. }
  220. return &withExemplarsMetric{Metric: m, exemplars: exs}, nil
  221. }
  222. // MustNewMetricWithExemplars is a version of NewMetricWithExemplars that panics where
  223. // NewMetricWithExemplars would have returned an error.
  224. func MustNewMetricWithExemplars(m Metric, exemplars ...Exemplar) Metric {
  225. ret, err := NewMetricWithExemplars(m, exemplars...)
  226. if err != nil {
  227. panic(err)
  228. }
  229. return ret
  230. }