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