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.

257 rivejä
9.1 KiB

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