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.
 
 

255 lines
8.9 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. 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. }
  88. // BuildFQName joins the given three name components by "_". Empty name
  89. // components are ignored. If the name parameter itself is empty, an empty
  90. // string is returned, no matter what. Metric implementations included in this
  91. // library use this function internally to generate the fully-qualified metric
  92. // name from the name component in their Opts. Users of the library will only
  93. // need this function if they implement their own Metric or instantiate a Desc
  94. // (with NewDesc) directly.
  95. func BuildFQName(namespace, subsystem, name string) string {
  96. if name == "" {
  97. return ""
  98. }
  99. switch {
  100. case namespace != "" && subsystem != "":
  101. return strings.Join([]string{namespace, subsystem, name}, "_")
  102. case namespace != "":
  103. return strings.Join([]string{namespace, name}, "_")
  104. case subsystem != "":
  105. return strings.Join([]string{subsystem, name}, "_")
  106. }
  107. return name
  108. }
  109. type invalidMetric struct {
  110. desc *Desc
  111. err error
  112. }
  113. // NewInvalidMetric returns a metric whose Write method always returns the
  114. // provided error. It is useful if a Collector finds itself unable to collect
  115. // a metric and wishes to report an error to the registry.
  116. func NewInvalidMetric(desc *Desc, err error) Metric {
  117. return &invalidMetric{desc, err}
  118. }
  119. func (m *invalidMetric) Desc() *Desc { return m.desc }
  120. func (m *invalidMetric) Write(*dto.Metric) error { return m.err }
  121. type timestampedMetric struct {
  122. Metric
  123. t time.Time
  124. }
  125. func (m timestampedMetric) Write(pb *dto.Metric) error {
  126. e := m.Metric.Write(pb)
  127. pb.TimestampMs = proto.Int64(m.t.Unix()*1000 + int64(m.t.Nanosecond()/1000000))
  128. return e
  129. }
  130. // NewMetricWithTimestamp returns a new Metric wrapping the provided Metric in a
  131. // way that it has an explicit timestamp set to the provided Time. This is only
  132. // useful in rare cases as the timestamp of a Prometheus metric should usually
  133. // be set by the Prometheus server during scraping. Exceptions include mirroring
  134. // metrics with given timestamps from other metric
  135. // sources.
  136. //
  137. // NewMetricWithTimestamp works best with MustNewConstMetric,
  138. // MustNewConstHistogram, and MustNewConstSummary, see example.
  139. //
  140. // Currently, the exposition formats used by Prometheus are limited to
  141. // millisecond resolution. Thus, the provided time will be rounded down to the
  142. // next full millisecond value.
  143. func NewMetricWithTimestamp(t time.Time, m Metric) Metric {
  144. return timestampedMetric{Metric: m, t: t}
  145. }
  146. type withExemplarsMetric struct {
  147. Metric
  148. exemplars []*dto.Exemplar
  149. }
  150. func (m *withExemplarsMetric) Write(pb *dto.Metric) error {
  151. if err := m.Metric.Write(pb); err != nil {
  152. return err
  153. }
  154. switch {
  155. case pb.Counter != nil:
  156. pb.Counter.Exemplar = m.exemplars[len(m.exemplars)-1]
  157. case pb.Histogram != nil:
  158. for _, e := range m.exemplars {
  159. // pb.Histogram.Bucket are sorted by UpperBound.
  160. i := sort.Search(len(pb.Histogram.Bucket), func(i int) bool {
  161. return pb.Histogram.Bucket[i].GetUpperBound() >= e.GetValue()
  162. })
  163. if i < len(pb.Histogram.Bucket) {
  164. pb.Histogram.Bucket[i].Exemplar = e
  165. } else {
  166. // 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.
  167. b := &dto.Bucket{
  168. CumulativeCount: proto.Uint64(pb.Histogram.GetSampleCount()),
  169. UpperBound: proto.Float64(math.Inf(1)),
  170. Exemplar: e,
  171. }
  172. pb.Histogram.Bucket = append(pb.Histogram.Bucket, b)
  173. }
  174. }
  175. default:
  176. // TODO(bwplotka): Implement Gauge?
  177. return errors.New("cannot inject exemplar into Gauge, Summary or Untyped")
  178. }
  179. return nil
  180. }
  181. // Exemplar is easier to use, user-facing representation of *dto.Exemplar.
  182. type Exemplar struct {
  183. Value float64
  184. Labels Labels
  185. // Optional.
  186. // Default value (time.Time{}) indicates its empty, which should be
  187. // understood as time.Now() time at the moment of creation of metric.
  188. Timestamp time.Time
  189. }
  190. // NewMetricWithExemplars returns a new Metric wrapping the provided Metric with given
  191. // exemplars. Exemplars are validated.
  192. //
  193. // Only last applicable exemplar is injected from the list.
  194. // For example for Counter it means last exemplar is injected.
  195. // For Histogram, it means last applicable exemplar for each bucket is injected.
  196. //
  197. // NewMetricWithExemplars works best with MustNewConstMetric and
  198. // MustNewConstHistogram, see example.
  199. func NewMetricWithExemplars(m Metric, exemplars ...Exemplar) (Metric, error) {
  200. if len(exemplars) == 0 {
  201. return nil, errors.New("no exemplar was passed for NewMetricWithExemplars")
  202. }
  203. var (
  204. now = time.Now()
  205. exs = make([]*dto.Exemplar, len(exemplars))
  206. err error
  207. )
  208. for i, e := range exemplars {
  209. ts := e.Timestamp
  210. if ts == (time.Time{}) {
  211. ts = now
  212. }
  213. exs[i], err = newExemplar(e.Value, ts, e.Labels)
  214. if err != nil {
  215. return nil, err
  216. }
  217. }
  218. return &withExemplarsMetric{Metric: m, exemplars: exs}, nil
  219. }
  220. // MustNewMetricWithExemplars is a version of NewMetricWithExemplars that panics where
  221. // NewMetricWithExemplars would have returned an error.
  222. func MustNewMetricWithExemplars(m Metric, exemplars ...Exemplar) Metric {
  223. ret, err := NewMetricWithExemplars(m, exemplars...)
  224. if err != nil {
  225. panic(err)
  226. }
  227. return ret
  228. }