| 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 prometheus |
| 18 |
|
| 19 |
import ( |
| 20 |
"math" |
| 21 |
"reflect" |
| 22 |
"regexp" |
| 23 |
"runtime" |
| 24 |
"runtime/metrics" |
| 25 |
"sync" |
| 26 |
"testing" |
| 27 |
|
| 28 |
dto "github.com/prometheus/client_model/go" |
| 29 |
|
| 30 |
"github.com/prometheus/client_golang/prometheus/internal" |
| 31 |
) |
| 32 |
|
| 33 |
func TestRmForMemStats(t *testing.T) { |
| 34 |
descs := bestEffortLookupRM(rmNamesForMemStatsMetrics) |
| 35 |
|
| 36 |
if got, want := len(descs), len(rmNamesForMemStatsMetrics); got != want { |
| 37 |
t.Errorf("got %d, want %d metrics", got, want) |
| 38 |
} |
| 39 |
|
| 40 |
for _, d := range descs { |
| 41 |
// We don't expect histograms there. |
| 42 |
if d.Kind == metrics.KindFloat64Histogram { |
| 43 |
t.Errorf("we don't expect to use histograms for MemStats metrics, got %v", d.Name) |
| 44 |
} |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
func expectedBaseMetrics() map[string]struct{} { |
| 49 |
metrics := map[string]struct{}{} |
| 50 |
b := newBaseGoCollector() |
| 51 |
for _, m := range []string{ |
| 52 |
b.gcDesc.fqName, |
| 53 |
b.goInfoDesc.fqName, |
| 54 |
b.goroutinesDesc.fqName, |
| 55 |
b.gcLastTimeDesc.fqName, |
| 56 |
b.threadsDesc.fqName, |
| 57 |
} { |
| 58 |
metrics[m] = struct{}{} |
| 59 |
} |
| 60 |
return metrics |
| 61 |
} |
| 62 |
|
| 63 |
func addExpectedRuntimeMemStats(metrics map[string]struct{}) map[string]struct{} { |
| 64 |
for _, m := range goRuntimeMemStats() { |
| 65 |
metrics[m.desc.fqName] = struct{}{} |
| 66 |
} |
| 67 |
return metrics |
| 68 |
} |
| 69 |
|
| 70 |
func addExpectedRuntimeMetrics(metrics map[string]struct{}) map[string]struct{} { |
| 71 |
for _, m := range expectedRuntimeMetrics { |
| 72 |
metrics[m] = struct{}{} |
| 73 |
} |
| 74 |
return metrics |
| 75 |
} |
| 76 |
|
| 77 |
func addExpectedDefaultRuntimeMetrics(metrics map[string]struct{}) map[string]struct{} { |
| 78 |
for _, e := range expMetrics { |
| 79 |
metrics[e] = struct{}{} |
| 80 |
} |
| 81 |
return metrics |
| 82 |
} |
| 83 |
|
| 84 |
func TestGoCollector_ExposedMetrics(t *testing.T) { |
| 85 |
for _, tcase := range []struct { |
| 86 |
opts internal.GoCollectorOptions |
| 87 |
expectedFQNameSet map[string]struct{} |
| 88 |
}{ |
| 89 |
{ |
| 90 |
opts: internal.GoCollectorOptions{ |
| 91 |
DisableMemStatsLikeMetrics: true, |
| 92 |
}, |
| 93 |
expectedFQNameSet: expectedBaseMetrics(), |
| 94 |
}, |
| 95 |
{ |
| 96 |
// Default, only MemStats and default Runtime metrics. |
| 97 |
opts: defaultGoCollectorOptions(), |
| 98 |
expectedFQNameSet: addExpectedDefaultRuntimeMetrics(addExpectedRuntimeMemStats(expectedBaseMetrics())), |
| 99 |
}, |
| 100 |
{ |
| 101 |
// Get all runtime/metrics without MemStats. |
| 102 |
opts: internal.GoCollectorOptions{ |
| 103 |
DisableMemStatsLikeMetrics: true, |
| 104 |
RuntimeMetricRules: []internal.GoCollectorRule{ |
| 105 |
{Matcher: regexp.MustCompile("/.*")}, |
| 106 |
}, |
| 107 |
}, |
| 108 |
expectedFQNameSet: addExpectedRuntimeMetrics(expectedBaseMetrics()), |
| 109 |
}, |
| 110 |
{ |
| 111 |
// Get all runtime/metrics and MemStats. |
| 112 |
opts: internal.GoCollectorOptions{ |
| 113 |
RuntimeMetricRules: []internal.GoCollectorRule{ |
| 114 |
{Matcher: regexp.MustCompile("/.*")}, |
| 115 |
}, |
| 116 |
}, |
| 117 |
expectedFQNameSet: addExpectedRuntimeMemStats(addExpectedRuntimeMetrics(expectedBaseMetrics())), |
| 118 |
}, |
| 119 |
} { |
| 120 |
if ok := t.Run("", func(t *testing.T) { |
| 121 |
goMetrics := collectGoMetrics(t, tcase.opts) |
| 122 |
goMetricSet := make(map[string]Metric) |
| 123 |
for _, m := range goMetrics { |
| 124 |
goMetricSet[m.Desc().fqName] = m |
| 125 |
} |
| 126 |
|
| 127 |
for i := range goMetrics { |
| 128 |
name := goMetrics[i].Desc().fqName |
| 129 |
|
| 130 |
if _, ok := tcase.expectedFQNameSet[name]; !ok { |
| 131 |
t.Errorf("found unexpected metric %s", name) |
| 132 |
continue |
| 133 |
} |
| 134 |
} |
| 135 |
|
| 136 |
// Now iterate over the expected metrics and look for removals. |
| 137 |
for expectedName := range tcase.expectedFQNameSet { |
| 138 |
if _, ok := goMetricSet[expectedName]; !ok { |
| 139 |
t.Errorf("missing expected metric %s in collection", expectedName) |
| 140 |
continue |
| 141 |
} |
| 142 |
} |
| 143 |
}); !ok { |
| 144 |
return |
| 145 |
} |
| 146 |
} |
| 147 |
} |
| 148 |
|
| 149 |
var sink interface{} |
| 150 |
|
| 151 |
func TestBatchHistogram(t *testing.T) { |
| 152 |
goMetrics := collectGoMetrics(t, internal.GoCollectorOptions{ |
| 153 |
RuntimeMetricRules: []internal.GoCollectorRule{ |
| 154 |
{Matcher: regexp.MustCompile("/.*")}, |
| 155 |
}, |
| 156 |
}) |
| 157 |
|
| 158 |
var mhist Metric |
| 159 |
for _, m := range goMetrics { |
| 160 |
if m.Desc().fqName == "go_gc_heap_allocs_by_size_bytes" { |
| 161 |
mhist = m |
| 162 |
break |
| 163 |
} |
| 164 |
} |
| 165 |
if mhist == nil { |
| 166 |
t.Fatal("failed to find metric to test") |
| 167 |
} |
| 168 |
hist, ok := mhist.(*batchHistogram) |
| 169 |
if !ok { |
| 170 |
t.Fatal("found metric is not a runtime/metrics histogram") |
| 171 |
} |
| 172 |
|
| 173 |
// Make a bunch of allocations then do another collection. |
| 174 |
// |
| 175 |
// The runtime/metrics API tries to reuse memory where possible, |
| 176 |
// so make sure that we didn't hang on to any of that memory in |
| 177 |
// hist. |
| 178 |
countsCopy := make([]uint64, len(hist.counts)) |
| 179 |
copy(countsCopy, hist.counts) |
| 180 |
for i := 0; i < 100; i++ { |
| 181 |
sink = make([]byte, 128) |
| 182 |
} |
| 183 |
|
| 184 |
collectGoMetrics(t, defaultGoCollectorOptions()) |
| 185 |
for i, v := range hist.counts { |
| 186 |
if v != countsCopy[i] { |
| 187 |
t.Error("counts changed during new collection") |
| 188 |
break |
| 189 |
} |
| 190 |
} |
| 191 |
|
| 192 |
// Get the runtime/metrics copy. |
| 193 |
s := []metrics.Sample{ |
| 194 |
{Name: "/gc/heap/allocs-by-size:bytes"}, |
| 195 |
} |
| 196 |
metrics.Read(s) |
| 197 |
rmHist := s[0].Value.Float64Histogram() |
| 198 |
wantBuckets := internal.RuntimeMetricsBucketsForUnit(rmHist.Buckets, "bytes") |
| 199 |
// runtime/metrics histograms always have a +Inf bucket and are lower |
| 200 |
// bound inclusive. In contrast, we have an implicit +Inf bucket and |
| 201 |
// are upper bound inclusive, so we can chop off the first bucket |
| 202 |
// (since the conversion to upper bound inclusive will shift all buckets |
| 203 |
// down one index) and the +Inf for the last bucket. |
| 204 |
wantBuckets = wantBuckets[1 : len(wantBuckets)-1] |
| 205 |
|
| 206 |
// Check to make sure the output proto makes sense. |
| 207 |
pb := &dto.Metric{} |
| 208 |
hist.Write(pb) |
| 209 |
|
| 210 |
if math.IsInf(pb.Histogram.Bucket[len(pb.Histogram.Bucket)-1].GetUpperBound(), +1) { |
| 211 |
t.Errorf("found +Inf bucket") |
| 212 |
} |
| 213 |
if got := len(pb.Histogram.Bucket); got != len(wantBuckets) { |
| 214 |
t.Errorf("got %d buckets in protobuf, want %d", got, len(wantBuckets)) |
| 215 |
} |
| 216 |
for i, bucket := range pb.Histogram.Bucket { |
| 217 |
// runtime/metrics histograms are lower-bound inclusive, but we're |
| 218 |
// upper-bound inclusive. So just make sure the new inclusive upper |
| 219 |
// bound is somewhere close by (in some cases it's equal). |
| 220 |
wantBound := wantBuckets[i] |
| 221 |
if gotBound := *bucket.UpperBound; (wantBound-gotBound)/wantBound > 0.001 { |
| 222 |
t.Errorf("got bound %f, want within 0.1%% of %f", gotBound, wantBound) |
| 223 |
} |
| 224 |
// Make sure counts are cumulative. Because of the consistency guarantees |
| 225 |
// made by the runtime/metrics package, we're really not guaranteed to get |
| 226 |
// anything even remotely the same here. |
| 227 |
if i > 0 && *bucket.CumulativeCount < *pb.Histogram.Bucket[i-1].CumulativeCount { |
| 228 |
t.Error("cumulative counts are non-monotonic") |
| 229 |
} |
| 230 |
} |
| 231 |
} |
| 232 |
|
| 233 |
func collectGoMetrics(t *testing.T, opts internal.GoCollectorOptions) []Metric { |
| 234 |
t.Helper() |
| 235 |
|
| 236 |
c := NewGoCollector(func(o *internal.GoCollectorOptions) { |
| 237 |
o.DisableMemStatsLikeMetrics = opts.DisableMemStatsLikeMetrics |
| 238 |
o.RuntimeMetricSumForHist = opts.RuntimeMetricSumForHist |
| 239 |
o.RuntimeMetricRules = opts.RuntimeMetricRules |
| 240 |
}).(*goCollector) |
| 241 |
|
| 242 |
// Collect all metrics. |
| 243 |
ch := make(chan Metric) |
| 244 |
var wg sync.WaitGroup |
| 245 |
var metrics []Metric |
| 246 |
wg.Add(1) |
| 247 |
go func() { |
| 248 |
defer wg.Done() |
| 249 |
for metric := range ch { |
| 250 |
metrics = append(metrics, metric) |
| 251 |
} |
| 252 |
}() |
| 253 |
c.Collect(ch) |
| 254 |
close(ch) |
| 255 |
|
| 256 |
wg.Wait() |
| 257 |
|
| 258 |
return metrics |
| 259 |
} |
| 260 |
|
| 261 |
func TestMemStatsEquivalence(t *testing.T) { |
| 262 |
var msReal, msFake runtime.MemStats |
| 263 |
descs := bestEffortLookupRM(rmNamesForMemStatsMetrics) |
| 264 |
|
| 265 |
samples := make([]metrics.Sample, len(descs)) |
| 266 |
samplesMap := make(map[string]*metrics.Sample) |
| 267 |
for i := range descs { |
| 268 |
samples[i].Name = descs[i].Name |
| 269 |
samplesMap[descs[i].Name] = &samples[i] |
| 270 |
} |
| 271 |
|
| 272 |
// Force a GC cycle to try to reach a clean slate. |
| 273 |
runtime.GC() |
| 274 |
|
| 275 |
// Populate msReal. |
| 276 |
runtime.ReadMemStats(&msReal) |
| 277 |
// Populate msFake and hope that no GC happened in between (: |
| 278 |
metrics.Read(samples) |
| 279 |
|
| 280 |
memStatsFromRM(&msFake, samplesMap) |
| 281 |
|
| 282 |
// Iterate over them and make sure they're somewhat close. |
| 283 |
msRealValue := reflect.ValueOf(msReal) |
| 284 |
msFakeValue := reflect.ValueOf(msFake) |
| 285 |
|
| 286 |
typ := msRealValue.Type() |
| 287 |
for i := 0; i < msRealValue.NumField(); i++ { |
| 288 |
fr := msRealValue.Field(i) |
| 289 |
ff := msFakeValue.Field(i) |
| 290 |
|
| 291 |
if typ.Field(i).Name == "PauseTotalNs" || typ.Field(i).Name == "LastGC" { |
| 292 |
// We don't use those fields for metrics, |
| 293 |
// thus we are not interested in having this filled. |
| 294 |
continue |
| 295 |
} |
| 296 |
switch fr.Kind() { |
| 297 |
// Fields which we are interested in are all uint64s. |
| 298 |
// The only float64 field GCCPUFraction is by design omitted. |
| 299 |
case reflect.Uint64: |
| 300 |
vr := fr.Interface().(uint64) |
| 301 |
vf := ff.Interface().(uint64) |
| 302 |
if float64(vr-vf)/float64(vf) > 0.05 { |
| 303 |
t.Errorf("wrong value for %s: got %d, want %d", typ.Field(i).Name, vf, vr) |
| 304 |
} |
| 305 |
} |
| 306 |
} |
| 307 |
} |
| 308 |
|
| 309 |
func TestExpectedRuntimeMetrics(t *testing.T) { |
| 310 |
goMetrics := collectGoMetrics(t, internal.GoCollectorOptions{ |
| 311 |
DisableMemStatsLikeMetrics: true, |
| 312 |
RuntimeMetricRules: []internal.GoCollectorRule{ |
| 313 |
{Matcher: regexp.MustCompile("/.*")}, |
| 314 |
}, |
| 315 |
}) |
| 316 |
goMetricSet := make(map[string]Metric) |
| 317 |
for _, m := range goMetrics { |
| 318 |
goMetricSet[m.Desc().fqName] = m |
| 319 |
} |
| 320 |
|
| 321 |
descs := metrics.All() |
| 322 |
rmSet := make(map[string]struct{}) |
| 323 |
// Iterate over runtime-reported descriptions to find new metrics. |
| 324 |
for i := range descs { |
| 325 |
rmName := descs[i].Name |
| 326 |
rmSet[rmName] = struct{}{} |
| 327 |
|
| 328 |
// expectedRuntimeMetrics depends on Go version. |
| 329 |
expFQName, ok := expectedRuntimeMetrics[rmName] |
| 330 |
if !ok { |
| 331 |
t.Errorf("found new runtime/metrics metric %s", rmName) |
| 332 |
_, _, _, ok := internal.RuntimeMetricsToProm(&descs[i]) |
| 333 |
if !ok { |
| 334 |
t.Errorf("new metric has name that can't be converted, or has an unsupported Kind") |
| 335 |
} |
| 336 |
continue |
| 337 |
} |
| 338 |
_, ok = goMetricSet[expFQName] |
| 339 |
if !ok { |
| 340 |
t.Errorf("existing runtime/metrics metric %s (expected fq name %s) not collected", rmName, expFQName) |
| 341 |
continue |
| 342 |
} |
| 343 |
} |
| 344 |
|
| 345 |
// Now iterate over the expected metrics and look for removals. |
| 346 |
cardinality := 0 |
| 347 |
for rmName, fqName := range expectedRuntimeMetrics { |
| 348 |
if _, ok := rmSet[rmName]; !ok { |
| 349 |
t.Errorf("runtime/metrics metric %s removed", rmName) |
| 350 |
continue |
| 351 |
} |
| 352 |
if _, ok := goMetricSet[fqName]; !ok { |
| 353 |
t.Errorf("runtime/metrics metric %s not appearing under expected name %s", rmName, fqName) |
| 354 |
continue |
| 355 |
} |
| 356 |
|
| 357 |
// While we're at it, check to make sure expected cardinality lines |
| 358 |
// up, but at the point of the protobuf write to get as close to the |
| 359 |
// real deal as possible. |
| 360 |
// |
| 361 |
// Note that we filter out non-runtime/metrics metrics here, because |
| 362 |
// those are manually managed. |
| 363 |
var m dto.Metric |
| 364 |
if err := goMetricSet[fqName].Write(&m); err != nil { |
| 365 |
t.Errorf("writing metric %s: %v", fqName, err) |
| 366 |
continue |
| 367 |
} |
| 368 |
// N.B. These are the only fields populated by runtime/metrics metrics specifically. |
| 369 |
// Other fields are populated by e.g. GCStats metrics. |
| 370 |
switch { |
| 371 |
case m.Counter != nil: |
| 372 |
fallthrough |
| 373 |
case m.Gauge != nil: |
| 374 |
cardinality++ |
| 375 |
case m.Histogram != nil: |
| 376 |
cardinality += len(m.Histogram.Bucket) + 3 // + sum, count, and +inf |
| 377 |
default: |
| 378 |
t.Errorf("unexpected protobuf structure for metric %s", fqName) |
| 379 |
} |
| 380 |
} |
| 381 |
|
| 382 |
if t.Failed() { |
| 383 |
t.Log("a new Go version may have been detected, please run") |
| 384 |
t.Log("\tgo run gen_go_collector_metrics_set.go go1.X") |
| 385 |
t.Log("where X is the Go version you are currently using") |
| 386 |
} |
| 387 |
|
| 388 |
expectCardinality := expectedRuntimeMetricsCardinality |
| 389 |
if cardinality != expectCardinality { |
| 390 |
t.Errorf("unexpected cardinality for runtime/metrics metrics: got %d, want %d", cardinality, expectCardinality) |
| 391 |
} |
| 392 |
} |
| 393 |
|
| 394 |
func TestGoCollectorConcurrency(t *testing.T) { |
| 395 |
c := NewGoCollector().(*goCollector) |
| 396 |
|
| 397 |
// Set up multiple goroutines to Collect from the |
| 398 |
// same GoCollector. In race mode with GOMAXPROCS > 1, |
| 399 |
// this test should fail often if Collect is not |
| 400 |
// concurrent-safe. |
| 401 |
for i := 0; i < 4; i++ { |
| 402 |
go func() { |
| 403 |
ch := make(chan Metric) |
| 404 |
go func() { |
| 405 |
// Drain all metrics received until the |
| 406 |
// channel is closed. |
| 407 |
for range ch { |
| 408 |
} |
| 409 |
}() |
| 410 |
c.Collect(ch) |
| 411 |
close(ch) |
| 412 |
}() |
| 413 |
} |
| 414 |
} |