Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add default Go runtime metrics for /gc/gogc:percent, /gc/gomemlimit:bytes, /sched/gomaxprocs:threads #1559

Merged
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions prometheus/collectors/go_collector_latest.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,16 @@ func WithGoCollectorMemStatsMetricsDisabled() func(options *internal.GoCollector
}
}

// WithGoCollectorRuntimeEnvVarsMetricsDisabled disables the following default metrics:
// go_gogc_percent
// go_gomemlimit
// go_gomaxprocs
func WithGoCollectorRuntimeEnvVarsMetricsDisabled() func(options *internal.GoCollectorOptions) {
bwplotka marked this conversation as resolved.
Show resolved Hide resolved
return func(o *internal.GoCollectorOptions) {
o.DisableRuntimeEnvVarsMetrics = true
}
}

// GoRuntimeMetricsRule allow enabling and configuring particular group of runtime/metrics.
// TODO(bwplotka): Consider adding ability to adjust buckets.
type GoRuntimeMetricsRule struct {
Expand Down
6 changes: 5 additions & 1 deletion prometheus/collectors/go_collector_latest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,11 @@ func TestGoCollectorMarshalling(t *testing.T) {
}
}

func TestWithGoCollectorMemStatsMetricsDisabled(t *testing.T) {
func TestWithBaseMetricsOnly(t *testing.T) {
reg := prometheus.NewRegistry()
reg.MustRegister(NewGoCollector(
WithGoCollectorMemStatsMetricsDisabled(),
WithGoCollectorRuntimeEnvVarsMetricsDisabled(),
))
result, err := reg.Gather()
if err != nil {
Expand Down Expand Up @@ -117,6 +118,7 @@ func TestGoCollectorAllowList(t *testing.T) {
reg.MustRegister(NewGoCollector(
WithGoCollectorMemStatsMetricsDisabled(),
WithGoCollectorRuntimeMetrics(test.rules...),
WithGoCollectorRuntimeEnvVarsMetricsDisabled(),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we test somewhere how it looks with those enabled?

))
result, err := reg.Gather()
if err != nil {
Expand Down Expand Up @@ -171,6 +173,7 @@ func TestGoCollectorDenyList(t *testing.T) {
reg.MustRegister(NewGoCollector(
WithGoCollectorMemStatsMetricsDisabled(),
WithoutGoCollectorRuntimeMetrics(test.matchers...),
WithGoCollectorRuntimeEnvVarsMetricsDisabled(),
))
result, err := reg.Gather()
if err != nil {
Expand Down Expand Up @@ -214,6 +217,7 @@ func ExampleGoCollector_WithAdvancedGoMetrics() {
},
),
WithoutGoCollectorRuntimeMetrics(regexp.MustCompile("^/gc/.*")),
WithGoCollectorRuntimeEnvVarsMetricsDisabled(),
))

http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{}))
Expand Down
5 changes: 5 additions & 0 deletions prometheus/go_collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,3 +279,8 @@ type memStatsMetrics []struct {
eval func(*runtime.MemStats) float64
valType ValueType
}

type runtimeEnvVarsMetrics []struct { // I couldn't come up with a better name. Any suggestions?
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice! I see where you go with this. This way would totally work, but it's extra structures in many places. There is a way to simplify this by reusing generic flow, so by default adding appropriate regexes to RuntimeMetricRules in defaultGoCollectorOptions (also you can remove the weird dead code (comment)) -

func defaultGoCollectorOptions() internal.GoCollectorOptions {

I think we can add that by default, then fix tests. We could even test if WithoutGoCollectorRuntimeMetrics can turn those off 🤗 WDYT?

desc *Desc
origMetricName string
}
30 changes: 30 additions & 0 deletions prometheus/go_collector_go120.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// Copyright 2024 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build !go1.21
// +build !go1.21

package prometheus

func goRuntimeEnvVarsMetrics() runtimeEnvVarsMetrics {
return runtimeEnvVarsMetrics{
{
desc: NewDesc(
"go_gomaxprocs",
"Value of GOMAXPROCS, i.e number of usable threads.",
nil, nil,
),
origMetricName: "/sched/gomaxprocs:threads",
},
}
}
46 changes: 46 additions & 0 deletions prometheus/go_collector_go121.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Copyright 2024 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//go:build go1.21
// +build go1.21

package prometheus

func goRuntimeEnvVarsMetrics() runtimeEnvVarsMetrics {
return runtimeEnvVarsMetrics{
{
desc: NewDesc(
"go_gogc_percent",
"Value of GOGC (percentage).",
nil, nil,
),
origMetricName: "/gc/gogc:percent",
},
{
desc: NewDesc(
"go_gomemlimit",
"Value of GOMEMLIMIT (bytes).",
nil, nil,
),
origMetricName: "/gc/gomemlimit:bytes",
},
{
desc: NewDesc(
"go_gomaxprocs",
"Value of GOMAXPROCS, i.e number of usable threads.",
nil, nil,
),
origMetricName: "/sched/gomaxprocs:threads",
},
}
}
65 changes: 53 additions & 12 deletions prometheus/go_collector_latest.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
package prometheus

import (
"fmt"
"math"
"runtime"
"runtime/metrics"
Expand All @@ -31,13 +32,15 @@ import (

const (
// constants for strings referenced more than once.
goGCGogcPercent = "/gc/gogc:percent"
goGCHeapTinyAllocsObjects = "/gc/heap/tiny/allocs:objects"
goGCHeapAllocsObjects = "/gc/heap/allocs:objects"
goGCHeapFreesObjects = "/gc/heap/frees:objects"
goGCHeapFreesBytes = "/gc/heap/frees:bytes"
goGCHeapAllocsBytes = "/gc/heap/allocs:bytes"
goGCHeapObjects = "/gc/heap/objects:objects"
goGCHeapGoalBytes = "/gc/heap/goal:bytes"
goGCMemLimit = "/gc/gomemlimit:bytes"
goMemoryClassesTotalBytes = "/memory/classes/total:bytes"
goMemoryClassesHeapObjectsBytes = "/memory/classes/heap/objects:bytes"
goMemoryClassesHeapUnusedBytes = "/memory/classes/heap/unused:bytes"
Expand All @@ -52,6 +55,7 @@ const (
goMemoryClassesProfilingBucketsBytes = "/memory/classes/profiling/buckets:bytes"
goMemoryClassesMetadataOtherBytes = "/memory/classes/metadata/other:bytes"
goMemoryClassesOtherBytes = "/memory/classes/other:bytes"
goSchedMaxProcs = "/sched/gomaxprocs:threads"
)

// rmNamesForMemStatsMetrics represents runtime/metrics names required to populate goRuntimeMemStats from like logic.
Expand All @@ -78,6 +82,12 @@ var rmNamesForMemStatsMetrics = []string{
goMemoryClassesOtherBytes,
}

var rmNamesForEnvVarsMetrics = []string{ // how to name this var???
goGCGogcPercent,
goGCMemLimit,
goSchedMaxProcs,
}

func bestEffortLookupRM(lookup []string) []metrics.Description {
ret := make([]metrics.Description, 0, len(lookup))
for _, rm := range metrics.All() {
Expand Down Expand Up @@ -116,6 +126,9 @@ type goCollector struct {
// as well.
msMetrics memStatsMetrics
msMetricsEnabled bool

rmEnvVarsMetrics runtimeEnvVarsMetrics // how to call them???
rmEnvVarsMetricsEnabled bool
}

type rmMetricDesc struct {
Expand Down Expand Up @@ -193,7 +206,7 @@ func NewGoCollector(opts ...func(o *internal.GoCollectorOptions)) Collector {
metricSet := make([]collectorMetric, 0, len(exposedDescriptions))
// SampleBuf is used for reading from runtime/metrics.
// We are assuming the largest case to have stable pointers for sampleMap purposes.
sampleBuf := make([]metrics.Sample, 0, len(exposedDescriptions)+len(opt.RuntimeMetricSumForHist)+len(rmNamesForMemStatsMetrics))
sampleBuf := make([]metrics.Sample, 0, len(exposedDescriptions)+len(opt.RuntimeMetricSumForHist)+len(rmNamesForMemStatsMetrics)+len(rmNamesForEnvVarsMetrics))
sampleMap := make(map[string]*metrics.Sample, len(exposedDescriptions))
for _, d := range exposedDescriptions {
namespace, subsystem, name, ok := internal.RuntimeMetricsToProm(&d.Description)
Expand Down Expand Up @@ -255,8 +268,10 @@ func NewGoCollector(opts ...func(o *internal.GoCollectorOptions)) Collector {
}

var (
msMetrics memStatsMetrics
msDescriptions []metrics.Description
msMetrics memStatsMetrics
msDescriptions []metrics.Description
rmEnvVarsMetrics runtimeEnvVarsMetrics
rmEnvVarsDescriptions []metrics.Description
)

if !opt.DisableMemStatsLikeMetrics {
Expand All @@ -273,14 +288,29 @@ func NewGoCollector(opts ...func(o *internal.GoCollectorOptions)) Collector {
}
}

if !opt.DisableRuntimeEnvVarsMetrics {
rmEnvVarsMetrics = goRuntimeEnvVarsMetrics()
rmEnvVarsDescriptions = bestEffortLookupRM(rmNamesForEnvVarsMetrics)

// Check if metric was not exposed before and if not, add to sampleBuf.
for _, rnevDesc := range rmEnvVarsDescriptions {
if _, ok := sampleMap[rnevDesc.Name]; ok {
continue
}
sampleBuf = append(sampleBuf, metrics.Sample{Name: rnevDesc.Name})
sampleMap[rnevDesc.Name] = &sampleBuf[len(sampleBuf)-1]
}
}
return &goCollector{
base: newBaseGoCollector(),
sampleBuf: sampleBuf,
sampleMap: sampleMap,
rmExposedMetrics: metricSet,
rmExactSumMapForHist: opt.RuntimeMetricSumForHist,
msMetrics: msMetrics,
msMetricsEnabled: !opt.DisableMemStatsLikeMetrics,
base: newBaseGoCollector(),
sampleBuf: sampleBuf,
sampleMap: sampleMap,
rmExposedMetrics: metricSet,
rmExactSumMapForHist: opt.RuntimeMetricSumForHist,
msMetrics: msMetrics,
msMetricsEnabled: !opt.DisableMemStatsLikeMetrics,
rmEnvVarsMetrics: rmEnvVarsMetrics,
rmEnvVarsMetricsEnabled: !opt.DisableRuntimeEnvVarsMetrics,
}
}

Expand Down Expand Up @@ -360,6 +390,17 @@ func (c *goCollector) Collect(ch chan<- Metric) {
ch <- MustNewConstMetric(i.desc, i.valType, i.eval(&ms))
}
}

if c.rmEnvVarsMetricsEnabled {
sampleBuf := make([]metrics.Sample, len(c.rmEnvVarsMetrics))
for i, v := range c.rmEnvVarsMetrics {
sampleBuf[i].Name = v.origMetricName
}
metrics.Read(sampleBuf)
for i, v := range c.rmEnvVarsMetrics {
ch <- MustNewConstMetric(v.desc, GaugeValue, unwrapScalarRMValue(sampleBuf[i].Value))
}
}
}

// unwrapScalarRMValue unwraps a runtime/metrics value that is assumed
Expand All @@ -376,13 +417,13 @@ func unwrapScalarRMValue(v metrics.Value) float64 {
//
// This should never happen because we always populate our metric
// set from the runtime/metrics package.
panic("unexpected unsupported metric")
panic("unexpected bad kind metric")
default:
// Unsupported metric kind.
//
// This should never happen because we check for this during initialization
// and flag and filter metrics whose kinds we don't understand.
panic("unexpected unsupported metric kind")
panic(fmt.Sprintf("unexpected unsupported metric: %v", v.Kind()))
}
}

Expand Down
36 changes: 30 additions & 6 deletions prometheus/go_collector_latest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,39 +74,62 @@ func addExpectedRuntimeMetrics(metrics map[string]struct{}) map[string]struct{}
return metrics
}

func addExpectedEnvVarsMetrics(metrics map[string]struct{}) map[string]struct{} {
for _, m := range goRuntimeEnvVarsMetrics() {
metrics[m.desc.fqName] = struct{}{}
}
return metrics
}

func TestGoCollector_ExposedMetrics(t *testing.T) {
for _, tcase := range []struct {
opts internal.GoCollectorOptions
expectedFQNameSet map[string]struct{}
}{
{
opts: internal.GoCollectorOptions{
DisableMemStatsLikeMetrics: true,
DisableMemStatsLikeMetrics: true,
DisableRuntimeEnvVarsMetrics: true,
},
expectedFQNameSet: expectedBaseMetrics(),
},
{
// Default, only MemStats.
// Default, only Memstats and RuntimeEnvVars.
expectedFQNameSet: addExpectedEnvVarsMetrics(addExpectedRuntimeMemStats(expectedBaseMetrics())),
},
{
// Only MemStats.
opts: internal.GoCollectorOptions{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let's use default function then?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mind using our new internal.GoCollector default etc here?

DisableRuntimeEnvVarsMetrics: true,
},
expectedFQNameSet: addExpectedRuntimeMemStats(expectedBaseMetrics()),
},
{
// Get all runtime/metrics without MemStats.
// Get all runtime/metrics without MemStats nor RuntimeEnvVars.
opts: internal.GoCollectorOptions{
DisableMemStatsLikeMetrics: true,
DisableMemStatsLikeMetrics: true,
DisableRuntimeEnvVarsMetrics: true,
RuntimeMetricRules: []internal.GoCollectorRule{
{Matcher: regexp.MustCompile("/.*")},
},
},
expectedFQNameSet: addExpectedRuntimeMetrics(expectedBaseMetrics()),
},
{
// Get all runtime/metrics and MemStats.
// Get all runtime/metrics, MemStats and RuntimeEnvVars.
opts: internal.GoCollectorOptions{
RuntimeMetricRules: []internal.GoCollectorRule{
{Matcher: regexp.MustCompile("/.*")},
},
},
expectedFQNameSet: addExpectedRuntimeMemStats(addExpectedRuntimeMetrics(expectedBaseMetrics())),
expectedFQNameSet: addExpectedEnvVarsMetrics(addExpectedRuntimeMemStats(addExpectedRuntimeMetrics(expectedBaseMetrics()))),
},
{
// Only RuntimeEnvVars.
opts: internal.GoCollectorOptions{
DisableMemStatsLikeMetrics: true,
},
expectedFQNameSet: addExpectedEnvVarsMetrics(expectedBaseMetrics()),
},
} {
if ok := t.Run("", func(t *testing.T) {
Expand Down Expand Up @@ -229,6 +252,7 @@ func collectGoMetrics(t *testing.T, opts internal.GoCollectorOptions) []Metric {
o.DisableMemStatsLikeMetrics = opts.DisableMemStatsLikeMetrics
o.RuntimeMetricSumForHist = opts.RuntimeMetricSumForHist
o.RuntimeMetricRules = opts.RuntimeMetricRules
o.DisableRuntimeEnvVarsMetrics = opts.DisableRuntimeEnvVarsMetrics
}).(*goCollector)

// Collect all metrics.
Expand Down
7 changes: 4 additions & 3 deletions prometheus/internal/go_collector_options.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ type GoCollectorRule struct {
//
// This is internal, so external users only can use it via `collector.WithGoCollector*` methods
type GoCollectorOptions struct {
DisableMemStatsLikeMetrics bool
RuntimeMetricSumForHist map[string]string
RuntimeMetricRules []GoCollectorRule
DisableMemStatsLikeMetrics bool
RuntimeMetricSumForHist map[string]string
RuntimeMetricRules []GoCollectorRule
DisableRuntimeEnvVarsMetrics bool
}
Loading