Tizen_4.0 base
[platform/upstream/docker-engine.git] / vendor / github.com / prometheus / client_golang / prometheus / vec.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         "fmt"
18         "sync"
19 )
20
21 // MetricVec is a Collector to bundle metrics of the same name that
22 // differ in their label values. MetricVec is usually not used directly but as a
23 // building block for implementations of vectors of a given metric
24 // type. GaugeVec, CounterVec, SummaryVec, and UntypedVec are examples already
25 // provided in this package.
26 type MetricVec struct {
27         mtx      sync.RWMutex // Protects the children.
28         children map[uint64]Metric
29         desc     *Desc
30
31         newMetric func(labelValues ...string) Metric
32 }
33
34 // Describe implements Collector. The length of the returned slice
35 // is always one.
36 func (m *MetricVec) Describe(ch chan<- *Desc) {
37         ch <- m.desc
38 }
39
40 // Collect implements Collector.
41 func (m *MetricVec) Collect(ch chan<- Metric) {
42         m.mtx.RLock()
43         defer m.mtx.RUnlock()
44
45         for _, metric := range m.children {
46                 ch <- metric
47         }
48 }
49
50 // GetMetricWithLabelValues returns the Metric for the given slice of label
51 // values (same order as the VariableLabels in Desc). If that combination of
52 // label values is accessed for the first time, a new Metric is created.
53 //
54 // It is possible to call this method without using the returned Metric to only
55 // create the new Metric but leave it at its start value (e.g. a Summary or
56 // Histogram without any observations). See also the SummaryVec example.
57 //
58 // Keeping the Metric for later use is possible (and should be considered if
59 // performance is critical), but keep in mind that Reset, DeleteLabelValues and
60 // Delete can be used to delete the Metric from the MetricVec. In that case, the
61 // Metric will still exist, but it will not be exported anymore, even if a
62 // Metric with the same label values is created later. See also the CounterVec
63 // example.
64 //
65 // An error is returned if the number of label values is not the same as the
66 // number of VariableLabels in Desc.
67 //
68 // Note that for more than one label value, this method is prone to mistakes
69 // caused by an incorrect order of arguments. Consider GetMetricWith(Labels) as
70 // an alternative to avoid that type of mistake. For higher label numbers, the
71 // latter has a much more readable (albeit more verbose) syntax, but it comes
72 // with a performance overhead (for creating and processing the Labels map).
73 // See also the GaugeVec example.
74 func (m *MetricVec) GetMetricWithLabelValues(lvs ...string) (Metric, error) {
75         h, err := m.hashLabelValues(lvs)
76         if err != nil {
77                 return nil, err
78         }
79
80         m.mtx.RLock()
81         metric, ok := m.children[h]
82         m.mtx.RUnlock()
83         if ok {
84                 return metric, nil
85         }
86
87         m.mtx.Lock()
88         defer m.mtx.Unlock()
89         return m.getOrCreateMetric(h, lvs...), nil
90 }
91
92 // GetMetricWith returns the Metric for the given Labels map (the label names
93 // must match those of the VariableLabels in Desc). If that label map is
94 // accessed for the first time, a new Metric is created. Implications of
95 // creating a Metric without using it and keeping the Metric for later use are
96 // the same as for GetMetricWithLabelValues.
97 //
98 // An error is returned if the number and names of the Labels are inconsistent
99 // with those of the VariableLabels in Desc.
100 //
101 // This method is used for the same purpose as
102 // GetMetricWithLabelValues(...string). See there for pros and cons of the two
103 // methods.
104 func (m *MetricVec) GetMetricWith(labels Labels) (Metric, error) {
105         h, err := m.hashLabels(labels)
106         if err != nil {
107                 return nil, err
108         }
109
110         m.mtx.RLock()
111         metric, ok := m.children[h]
112         m.mtx.RUnlock()
113         if ok {
114                 return metric, nil
115         }
116
117         lvs := make([]string, len(labels))
118         for i, label := range m.desc.variableLabels {
119                 lvs[i] = labels[label]
120         }
121         m.mtx.Lock()
122         defer m.mtx.Unlock()
123         return m.getOrCreateMetric(h, lvs...), nil
124 }
125
126 // WithLabelValues works as GetMetricWithLabelValues, but panics if an error
127 // occurs. The method allows neat syntax like:
128 //     httpReqs.WithLabelValues("404", "POST").Inc()
129 func (m *MetricVec) WithLabelValues(lvs ...string) Metric {
130         metric, err := m.GetMetricWithLabelValues(lvs...)
131         if err != nil {
132                 panic(err)
133         }
134         return metric
135 }
136
137 // With works as GetMetricWith, but panics if an error occurs. The method allows
138 // neat syntax like:
139 //     httpReqs.With(Labels{"status":"404", "method":"POST"}).Inc()
140 func (m *MetricVec) With(labels Labels) Metric {
141         metric, err := m.GetMetricWith(labels)
142         if err != nil {
143                 panic(err)
144         }
145         return metric
146 }
147
148 // DeleteLabelValues removes the metric where the variable labels are the same
149 // as those passed in as labels (same order as the VariableLabels in Desc). It
150 // returns true if a metric was deleted.
151 //
152 // It is not an error if the number of label values is not the same as the
153 // number of VariableLabels in Desc.  However, such inconsistent label count can
154 // never match an actual Metric, so the method will always return false in that
155 // case.
156 //
157 // Note that for more than one label value, this method is prone to mistakes
158 // caused by an incorrect order of arguments. Consider Delete(Labels) as an
159 // alternative to avoid that type of mistake. For higher label numbers, the
160 // latter has a much more readable (albeit more verbose) syntax, but it comes
161 // with a performance overhead (for creating and processing the Labels map).
162 // See also the CounterVec example.
163 func (m *MetricVec) DeleteLabelValues(lvs ...string) bool {
164         m.mtx.Lock()
165         defer m.mtx.Unlock()
166
167         h, err := m.hashLabelValues(lvs)
168         if err != nil {
169                 return false
170         }
171         if _, ok := m.children[h]; !ok {
172                 return false
173         }
174         delete(m.children, h)
175         return true
176 }
177
178 // Delete deletes the metric where the variable labels are the same as those
179 // passed in as labels. It returns true if a metric was deleted.
180 //
181 // It is not an error if the number and names of the Labels are inconsistent
182 // with those of the VariableLabels in the Desc of the MetricVec. However, such
183 // inconsistent Labels can never match an actual Metric, so the method will
184 // always return false in that case.
185 //
186 // This method is used for the same purpose as DeleteLabelValues(...string). See
187 // there for pros and cons of the two methods.
188 func (m *MetricVec) Delete(labels Labels) bool {
189         m.mtx.Lock()
190         defer m.mtx.Unlock()
191
192         h, err := m.hashLabels(labels)
193         if err != nil {
194                 return false
195         }
196         if _, ok := m.children[h]; !ok {
197                 return false
198         }
199         delete(m.children, h)
200         return true
201 }
202
203 // Reset deletes all metrics in this vector.
204 func (m *MetricVec) Reset() {
205         m.mtx.Lock()
206         defer m.mtx.Unlock()
207
208         for h := range m.children {
209                 delete(m.children, h)
210         }
211 }
212
213 func (m *MetricVec) hashLabelValues(vals []string) (uint64, error) {
214         if len(vals) != len(m.desc.variableLabels) {
215                 return 0, errInconsistentCardinality
216         }
217         h := hashNew()
218         for _, val := range vals {
219                 h = hashAdd(h, val)
220         }
221         return h, nil
222 }
223
224 func (m *MetricVec) hashLabels(labels Labels) (uint64, error) {
225         if len(labels) != len(m.desc.variableLabels) {
226                 return 0, errInconsistentCardinality
227         }
228         h := hashNew()
229         for _, label := range m.desc.variableLabels {
230                 val, ok := labels[label]
231                 if !ok {
232                         return 0, fmt.Errorf("label name %q missing in label map", label)
233                 }
234                 h = hashAdd(h, val)
235         }
236         return h, nil
237 }
238
239 func (m *MetricVec) getOrCreateMetric(hash uint64, labelValues ...string) Metric {
240         metric, ok := m.children[hash]
241         if !ok {
242                 // Copy labelValues. Otherwise, they would be allocated even if we don't go
243                 // down this code path.
244                 copiedLabelValues := append(make([]string, 0, len(labelValues)), labelValues...)
245                 metric = m.newMetric(copiedLabelValues...)
246                 m.children[hash] = metric
247         }
248         return metric
249 }