Debian Codegraph @

prometheus/collectors/go_collector_latest_test.go

raw
1 // Copyright 2021 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 //go:build go1.17
15 // +build go1.17
16
17 package collectors
18
19 import (
20 "encoding/json"
21 "log"
22 "net/http"
23 "regexp"
24 "sort"
25 "testing"
26
27 "github.com/google/go-cmp/cmp"
28
29 "github.com/prometheus/client_golang/prometheus"
30 "github.com/prometheus/client_golang/prometheus/promhttp"
31 )
32
33 var baseMetrics = []string{
34 "go_gc_duration_seconds",
35 "go_goroutines",
36 "go_info",
37 "go_memstats_last_gc_time_seconds",
38 "go_threads",
39 }
40
41 var memstatMetrics = []string{
42 "go_memstats_alloc_bytes",
43 "go_memstats_alloc_bytes_total",
44 "go_memstats_buck_hash_sys_bytes",
45 "go_memstats_frees_total",
46 "go_memstats_gc_sys_bytes",
47 "go_memstats_heap_alloc_bytes",
48 "go_memstats_heap_idle_bytes",
49 "go_memstats_heap_inuse_bytes",
50 "go_memstats_heap_objects",
51 "go_memstats_heap_released_bytes",
52 "go_memstats_heap_sys_bytes",
53 "go_memstats_mallocs_total",
54 "go_memstats_mcache_inuse_bytes",
55 "go_memstats_mcache_sys_bytes",
56 "go_memstats_mspan_inuse_bytes",
57 "go_memstats_mspan_sys_bytes",
58 "go_memstats_next_gc_bytes",
59 "go_memstats_other_sys_bytes",
60 "go_memstats_stack_inuse_bytes",
61 "go_memstats_stack_sys_bytes",
62 "go_memstats_sys_bytes",
63 }
64
65 func withDefaultRuntimeMetrics(metricNames []string, withoutGC, withoutSched bool) []string {
66 switch {
67 case withoutGC && !withoutSched:
68 // If only withoutGC is true, exclude "go_gc_*" metrics.
69 metricNames = append(metricNames, onlySchedDefRuntimeMetrics...)
70 case withoutSched && !withoutGC:
71 // If only withoutSched is true, exclude "go_sched_*" metrics.
72 metricNames = append(metricNames, onlyGCDefRuntimeMetrics...)
73 default:
74 // In any other case, use the default metrics.
75 metricNames = append(metricNames, defaultRuntimeMetrics...)
76 }
77 // sorting is required
78 sort.Strings(metricNames)
79 return metricNames
80 }
81
82 func TestGoCollectorMarshalling(t *testing.T) {
83 reg := prometheus.NewPedanticRegistry()
84 reg.MustRegister(NewGoCollector(
85 WithGoCollectorRuntimeMetrics(GoRuntimeMetricsRule{
86 Matcher: regexp.MustCompile("/.*"),
87 }),
88 ))
89 result, err := reg.Gather()
90 if err != nil {
91 t.Fatal(err)
92 }
93
94 if _, err := json.Marshal(result); err != nil {
95 t.Errorf("json marshalling should not fail, %v", err)
96 }
97 }
98
99 func TestWithGoCollectorDefault(t *testing.T) {
100 reg := prometheus.NewPedanticRegistry()
101 reg.MustRegister(NewGoCollector())
102 result, err := reg.Gather()
103 if err != nil {
104 t.Fatal(err)
105 }
106
107 got := []string{}
108 for _, r := range result {
109 got = append(got, r.GetName())
110 }
111
112 expected := append(withBaseMetrics(memstatMetrics), defaultRuntimeMetrics...)
113 sort.Strings(expected)
114 if diff := cmp.Diff(got, expected); diff != "" {
115 t.Errorf("[IMPORTANT, those are default metrics, can't change in 1.x] missmatch (-want +got):\n%s", diff)
116 }
117 }
118
119 func TestWithGoCollectorMemStatsMetricsDisabled(t *testing.T) {
120 reg := prometheus.NewPedanticRegistry()
121 reg.MustRegister(NewGoCollector(
122 WithGoCollectorMemStatsMetricsDisabled(),
123 ))
124 result, err := reg.Gather()
125 if err != nil {
126 t.Fatal(err)
127 }
128
129 got := []string{}
130 for _, r := range result {
131 got = append(got, r.GetName())
132 }
133
134 if diff := cmp.Diff(got, withBaseMetrics(defaultRuntimeMetrics)); diff != "" {
135 t.Errorf("missmatch (-want +got):\n%s", diff)
136 }
137 }
138
139 func TestGoCollectorAllowList(t *testing.T) {
140 for _, test := range []struct {
141 name string
142 rules []GoRuntimeMetricsRule
143 expected []string
144 }{
145 {
146 name: "Without any rules",
147 rules: nil,
148 expected: withBaseMetrics(defaultRuntimeMetrics),
149 },
150 {
151 name: "allow all",
152 rules: []GoRuntimeMetricsRule{MetricsAll},
153 expected: withAllMetrics(),
154 },
155 {
156 name: "allow GC",
157 rules: []GoRuntimeMetricsRule{MetricsGC},
158 expected: withDefaultRuntimeMetrics(withGCMetrics(), true, false),
159 },
160 {
161 name: "allow Memory",
162 rules: []GoRuntimeMetricsRule{MetricsMemory},
163 expected: withDefaultRuntimeMetrics(withMemoryMetrics(), false, false),
164 },
165 {
166 name: "allow Scheduler",
167 rules: []GoRuntimeMetricsRule{MetricsScheduler},
168 expected: withDefaultRuntimeMetrics(withSchedulerMetrics(), false, true),
169 },
170 {
171 name: "allow debug",
172 rules: []GoRuntimeMetricsRule{MetricsDebug},
173 expected: withDefaultRuntimeMetrics(withDebugMetrics(), false, false),
174 },
175 } {
176 t.Run(test.name, func(t *testing.T) {
177 reg := prometheus.NewPedanticRegistry()
178 reg.MustRegister(NewGoCollector(
179 WithGoCollectorMemStatsMetricsDisabled(),
180 WithGoCollectorRuntimeMetrics(test.rules...),
181 ))
182 result, err := reg.Gather()
183 if err != nil {
184 t.Fatal(err)
185 }
186
187 got := []string{}
188 for _, r := range result {
189 got = append(got, r.GetName())
190 }
191
192 if diff := cmp.Diff(got, test.expected); diff != "" {
193 t.Errorf("missmatch (-want +got):\n%s", diff)
194 }
195 })
196 }
197 }
198
199 func withBaseMetrics(metricNames []string) []string {
200 metricNames = append(metricNames, baseMetrics...)
201 sort.Strings(metricNames)
202 return metricNames
203 }
204
205 func TestGoCollectorDenyList(t *testing.T) {
206 for _, test := range []struct {
207 name string
208 matchers []*regexp.Regexp
209 expected []string
210 }{
211 {
212 name: "Without any matchers",
213 matchers: nil,
214 expected: withBaseMetrics(defaultRuntimeMetrics),
215 },
216 {
217 name: "deny all",
218 matchers: []*regexp.Regexp{regexp.MustCompile("/.*")},
219 expected: baseMetrics,
220 },
221 {
222 name: "deny gc and scheduler latency",
223 matchers: []*regexp.Regexp{
224 regexp.MustCompile("^/gc/.*"),
225 regexp.MustCompile("^/sched/latencies:.*"),
226 },
227 expected: withDefaultRuntimeMetrics(baseMetrics, true, false),
228 },
229 {
230 name: "deny gc and scheduler",
231 matchers: []*regexp.Regexp{
232 regexp.MustCompile("^/gc/.*"),
233 regexp.MustCompile("^/sched/.*"),
234 },
235 expected: baseMetrics,
236 },
237 } {
238 t.Run(test.name, func(t *testing.T) {
239 reg := prometheus.NewPedanticRegistry()
240 reg.MustRegister(NewGoCollector(
241 WithGoCollectorMemStatsMetricsDisabled(),
242 WithoutGoCollectorRuntimeMetrics(test.matchers...),
243 ))
244 result, err := reg.Gather()
245 if err != nil {
246 t.Fatal(err)
247 }
248
249 got := []string{}
250 for _, r := range result {
251 got = append(got, r.GetName())
252 }
253
254 if diff := cmp.Diff(got, test.expected); diff != "" {
255 t.Errorf("missmatch (-want +got):\n%s", diff)
256 }
257 })
258 }
259 }
260
261 func ExampleNewGoCollector() {
262 reg := prometheus.NewPedanticRegistry()
263
264 // Register the GoCollector with the default options. Only the base metrics, default runtime metrics and memstats are enabled.
265 reg.MustRegister(NewGoCollector())
266
267 http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
268 log.Fatal(http.ListenAndServe(":8080", nil))
269 }
270
271 func ExampleNewGoCollector_withAdvancedGoMetrics() {
272 reg := prometheus.NewPedanticRegistry()
273
274 // Enable Go metrics with pre-defined rules. Or your custom rules.
275 reg.MustRegister(
276 NewGoCollector(
277 WithGoCollectorMemStatsMetricsDisabled(),
278 WithGoCollectorRuntimeMetrics(
279 MetricsScheduler,
280 MetricsMemory,
281 GoRuntimeMetricsRule{
282 Matcher: regexp.MustCompile("^/mycustomrule.*"),
283 },
284 ),
285 WithoutGoCollectorRuntimeMetrics(regexp.MustCompile("^/gc/.*")),
286 ))
287
288 http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
289 log.Fatal(http.ListenAndServe(":8080", nil))
290 }
291
292 func ExampleNewGoCollector_defaultRegister() {
293 // Unregister the default GoCollector.
294 prometheus.Unregister(NewGoCollector())
295
296 // Register the default GoCollector with a custom config.
297 prometheus.MustRegister(NewGoCollector(WithGoCollectorRuntimeMetrics(
298 MetricsScheduler,
299 MetricsGC,
300 GoRuntimeMetricsRule{
301 Matcher: regexp.MustCompile("^/mycustomrule.*"),
302 },
303 ),
304 ))
305
306 http.Handle("/metrics", promhttp.Handler())
307 log.Fatal(http.ListenAndServe(":8080", nil))
308 }