Debian Codegraph @

prometheus/wrap.go

raw
1 // Copyright 2018 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 "sort"
19
20 "github.com/prometheus/client_golang/prometheus/internal"
21
22 dto "github.com/prometheus/client_model/go"
23 "google.golang.org/protobuf/proto"
24 )
25
26 // WrapRegistererWith returns a Registerer wrapping the provided
27 // Registerer. Collectors registered with the returned Registerer will be
28 // registered with the wrapped Registerer in a modified way. The modified
29 // Collector adds the provided Labels to all Metrics it collects (as
30 // ConstLabels). The Metrics collected by the unmodified Collector must not
31 // duplicate any of those labels. Wrapping a nil value is valid, resulting
32 // in a no-op Registerer.
33 //
34 // WrapRegistererWith provides a way to add fixed labels to a subset of
35 // Collectors. It should not be used to add fixed labels to all metrics
36 // exposed. See also
37 // https://prometheus.io/docs/instrumenting/writing_exporters/#target-labels-not-static-scraped-labels
38 //
39 // Conflicts between Collectors registered through the original Registerer with
40 // Collectors registered through the wrapping Registerer will still be
41 // detected. Any AlreadyRegisteredError returned by the Register method of
42 // either Registerer will contain the ExistingCollector in the form it was
43 // provided to the respective registry.
44 //
45 // The Collector example demonstrates a use of WrapRegistererWith.
46 func WrapRegistererWith(labels Labels, reg Registerer) Registerer {
47 return &wrappingRegisterer{
48 wrappedRegisterer: reg,
49 labels: labels,
50 }
51 }
52
53 // WrapRegistererWithPrefix returns a Registerer wrapping the provided
54 // Registerer. Collectors registered with the returned Registerer will be
55 // registered with the wrapped Registerer in a modified way. The modified
56 // Collector adds the provided prefix to the name of all Metrics it collects.
57 // Wrapping a nil value is valid, resulting in a no-op Registerer.
58 //
59 // WrapRegistererWithPrefix is useful to have one place to prefix all metrics of
60 // a sub-system. To make this work, register metrics of the sub-system with the
61 // wrapping Registerer returned by WrapRegistererWithPrefix. It is rarely useful
62 // to use the same prefix for all metrics exposed. In particular, do not prefix
63 // metric names that are standardized across applications, as that would break
64 // horizontal monitoring, for example the metrics provided by the Go collector
65 // (see NewGoCollector) and the process collector (see NewProcessCollector). (In
66 // fact, those metrics are already prefixed with "go_" or "process_",
67 // respectively.)
68 //
69 // Conflicts between Collectors registered through the original Registerer with
70 // Collectors registered through the wrapping Registerer will still be
71 // detected. Any AlreadyRegisteredError returned by the Register method of
72 // either Registerer will contain the ExistingCollector in the form it was
73 // provided to the respective registry.
74 func WrapRegistererWithPrefix(prefix string, reg Registerer) Registerer {
75 return &wrappingRegisterer{
76 wrappedRegisterer: reg,
77 prefix: prefix,
78 }
79 }
80
81 // WrapCollectorWith returns a Collector wrapping the provided Collector. The
82 // wrapped Collector will add the provided Labels to all Metrics it collects (as
83 // ConstLabels). The Metrics collected by the unmodified Collector must not
84 // duplicate any of those labels.
85 //
86 // WrapCollectorWith can be useful to work with multiple instances of a third
87 // party library that does not expose enough flexibility on the lifecycle of its
88 // registered metrics.
89 // For example, let's say you have a foo.New(reg Registerer) constructor that
90 // registers metrics but never unregisters them, and you want to create multiple
91 // instances of foo.Foo with different labels.
92 // The way to achieve that, is to create a new Registry, pass it to foo.New,
93 // then use WrapCollectorWith to wrap that Registry with the desired labels and
94 // register that as a collector in your main Registry.
95 // Then you can un-register the wrapped collector effectively un-registering the
96 // metrics registered by foo.New.
97 func WrapCollectorWith(labels Labels, c Collector) Collector {
98 return &wrappingCollector{
99 wrappedCollector: c,
100 labels: labels,
101 }
102 }
103
104 // WrapCollectorWithPrefix returns a Collector wrapping the provided Collector. The
105 // wrapped Collector will add the provided prefix to the name of all Metrics it collects.
106 //
107 // See the documentation of WrapCollectorWith for more details on the use case.
108 func WrapCollectorWithPrefix(prefix string, c Collector) Collector {
109 return &wrappingCollector{
110 wrappedCollector: c,
111 prefix: prefix,
112 }
113 }
114
115 type wrappingRegisterer struct {
116 wrappedRegisterer Registerer
117 prefix string
118 labels Labels
119 }
120
121 func (r *wrappingRegisterer) Register(c Collector) error {
122 if r.wrappedRegisterer == nil {
123 return nil
124 }
125 return r.wrappedRegisterer.Register(&wrappingCollector{
126 wrappedCollector: c,
127 prefix: r.prefix,
128 labels: r.labels,
129 })
130 }
131
132 func (r *wrappingRegisterer) MustRegister(cs ...Collector) {
133 if r.wrappedRegisterer == nil {
134 return
135 }
136 for _, c := range cs {
137 if err := r.Register(c); err != nil {
138 panic(err)
139 }
140 }
141 }
142
143 func (r *wrappingRegisterer) Unregister(c Collector) bool {
144 if r.wrappedRegisterer == nil {
145 return false
146 }
147 return r.wrappedRegisterer.Unregister(&wrappingCollector{
148 wrappedCollector: c,
149 prefix: r.prefix,
150 labels: r.labels,
151 })
152 }
153
154 type wrappingCollector struct {
155 wrappedCollector Collector
156 prefix string
157 labels Labels
158 }
159
160 func (c *wrappingCollector) Collect(ch chan<- Metric) {
161 wrappedCh := make(chan Metric)
162 go func() {
163 c.wrappedCollector.Collect(wrappedCh)
164 close(wrappedCh)
165 }()
166 for m := range wrappedCh {
167 ch <- &wrappingMetric{
168 wrappedMetric: m,
169 prefix: c.prefix,
170 labels: c.labels,
171 }
172 }
173 }
174
175 func (c *wrappingCollector) Describe(ch chan<- *Desc) {
176 wrappedCh := make(chan *Desc)
177 go func() {
178 c.wrappedCollector.Describe(wrappedCh)
179 close(wrappedCh)
180 }()
181 for desc := range wrappedCh {
182 ch <- wrapDesc(desc, c.prefix, c.labels)
183 }
184 }
185
186 func (c *wrappingCollector) unwrapRecursively() Collector {
187 switch wc := c.wrappedCollector.(type) {
188 case *wrappingCollector:
189 return wc.unwrapRecursively()
190 default:
191 return wc
192 }
193 }
194
195 type wrappingMetric struct {
196 wrappedMetric Metric
197 prefix string
198 labels Labels
199 }
200
201 func (m *wrappingMetric) Desc() *Desc {
202 return wrapDesc(m.wrappedMetric.Desc(), m.prefix, m.labels)
203 }
204
205 func (m *wrappingMetric) Write(out *dto.Metric) error {
206 if err := m.wrappedMetric.Write(out); err != nil {
207 return err
208 }
209 if len(m.labels) == 0 {
210 // No wrapping labels.
211 return nil
212 }
213 for ln, lv := range m.labels {
214 out.Label = append(out.Label, &dto.LabelPair{
215 Name: proto.String(ln),
216 Value: proto.String(lv),
217 })
218 }
219 sort.Sort(internal.LabelPairSorter(out.Label))
220 return nil
221 }
222
223 func wrapDesc(desc *Desc, prefix string, labels Labels) *Desc {
224 constLabels := Labels{}
225 for _, lp := range desc.constLabelPairs {
226 constLabels[*lp.Name] = *lp.Value
227 }
228 for ln, lv := range labels {
229 if _, alreadyUsed := constLabels[ln]; alreadyUsed {
230 return &Desc{
231 fqName: desc.fqName,
232 help: desc.help,
233 variableLabels: desc.variableLabels,
234 constLabelPairs: desc.constLabelPairs,
235 err: fmt.Errorf("attempted wrapping with already existing label name %q", ln),
236 }
237 }
238 constLabels[ln] = lv
239 }
240 // NewDesc will do remaining validations.
241 newDesc := V2.NewDesc(prefix+desc.fqName, desc.help, desc.variableLabels, constLabels)
242 // Propagate errors if there was any. This will override any errer
243 // created by NewDesc above, i.e. earlier errors get precedence.
244 if desc.err != nil {
245 newDesc.err = desc.err
246 }
247 return newDesc
248 }