Skip to content

Commit 22da949

Browse files
authored
Use the runtime/metrics package for the Go collector for 1.17+ (#955)
This change introduces use of the runtime/metrics package in place of runtime.MemStats for Go 1.17 or later. The runtime/metrics package was introduced in Go 1.16, but not all the old metrics were accounted for until 1.17. The runtime/metrics package offers several advantages over using runtime.MemStats: * The list of metrics and their descriptions are machine-readable, allowing new metrics to get added without any additional work. * Detailed histogram-based metrics are now available, offering much deeper insights into the Go runtime. * The runtime/metrics API is significantly more efficient than runtime.MemStats, even with the additional metrics added, because it does not require any stop-the-world events. That being said, integrating the package comes with some caveats, some of which were discussed in #842. Namely: * The old MemStats-based metrics need to continue working, so they're exported under their old names backed by equivalent runtime/metrics metrics. * Earlier versions of Go need to continue working, so the old code remains, but behind a build tag. Finally, a few notes about the implementation: * This change includes a whole bunch of refactoring to avoid significant code duplication. * This change adds a new histogram metric type specifically optimized for runtime/metrics histograms. This type's methods also include additional logic to deal with differences in bounds conventions. * This change makes a whole bunch of decisions about how runtime/metrics names are translated. * This change adds a `go generate` script to generate a list of expected runtime/metrics names for a given Go version for auditing. Users of new versions of Go will transparently be allowed to use new metrics, however. Signed-off-by: Michael Anthony Knyszek <[email protected]>
1 parent dc1559e commit 22da949

12 files changed

+1449
-383
lines changed

prometheus/build_info_collector.go

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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+
package prometheus
15+
16+
import "runtime/debug"
17+
18+
// NewBuildInfoCollector is the obsolete version of collectors.NewBuildInfoCollector.
19+
// See there for documentation.
20+
//
21+
// Deprecated: Use collectors.NewBuildInfoCollector instead.
22+
func NewBuildInfoCollector() Collector {
23+
path, version, sum := "unknown", "unknown", "unknown"
24+
if bi, ok := debug.ReadBuildInfo(); ok {
25+
path = bi.Main.Path
26+
version = bi.Main.Version
27+
sum = bi.Main.Sum
28+
}
29+
c := &selfCollector{MustNewConstMetric(
30+
NewDesc(
31+
"go_build_info",
32+
"Build information about the main Go module.",
33+
nil, Labels{"path": path, "version": version, "checksum": sum},
34+
),
35+
GaugeValue, 1)}
36+
c.init(c.self)
37+
return c
38+
}

prometheus/counter.go

+6-2
Original file line numberDiff line numberDiff line change
@@ -133,10 +133,14 @@ func (c *counter) Inc() {
133133
atomic.AddUint64(&c.valInt, 1)
134134
}
135135

136-
func (c *counter) Write(out *dto.Metric) error {
136+
func (c *counter) get() float64 {
137137
fval := math.Float64frombits(atomic.LoadUint64(&c.valBits))
138138
ival := atomic.LoadUint64(&c.valInt)
139-
val := fval + float64(ival)
139+
return fval + float64(ival)
140+
}
141+
142+
func (c *counter) Write(out *dto.Metric) error {
143+
val := c.get()
140144

141145
var exemplar *dto.Exemplar
142146
if e := c.exemplar.Load(); e != nil {
+115
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
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 ignore
15+
// +build ignore
16+
17+
package main
18+
19+
import (
20+
"bytes"
21+
"fmt"
22+
"go/format"
23+
"log"
24+
"os"
25+
"runtime/metrics"
26+
"strconv"
27+
"strings"
28+
"text/template"
29+
30+
"github.com/prometheus/client_golang/prometheus"
31+
"github.com/prometheus/client_golang/prometheus/internal"
32+
)
33+
34+
func main() {
35+
if len(os.Args) != 2 {
36+
log.Fatal("requires Go version (e.g. go1.17) as an argument")
37+
}
38+
version, err := parseVersion(os.Args[1])
39+
if err != nil {
40+
log.Fatalf("parsing Go version: %v", err)
41+
}
42+
43+
// Generate code.
44+
var buf bytes.Buffer
45+
err = testFile.Execute(&buf, struct {
46+
Descriptions []metrics.Description
47+
GoVersion goVersion
48+
}{
49+
Descriptions: metrics.All(),
50+
GoVersion: version,
51+
})
52+
if err != nil {
53+
log.Fatalf("executing template: %v", err)
54+
}
55+
56+
// Format it.
57+
result, err := format.Source(buf.Bytes())
58+
if err != nil {
59+
log.Fatalf("formatting code: %v", err)
60+
}
61+
62+
// Write it to a file.
63+
fname := fmt.Sprintf("go_collector_metrics_%s_test.go", version.Abbr())
64+
if err := os.WriteFile(fname, result, 0o644); err != nil {
65+
log.Fatalf("writing file: %v", err)
66+
}
67+
}
68+
69+
type goVersion int
70+
71+
func (g goVersion) String() string {
72+
return fmt.Sprintf("go1.%d", g)
73+
}
74+
75+
func (g goVersion) Abbr() string {
76+
return fmt.Sprintf("go1%d", g)
77+
}
78+
79+
func parseVersion(s string) (goVersion, error) {
80+
i := strings.IndexRune(s, '.')
81+
if i < 0 {
82+
return goVersion(-1), fmt.Errorf("bad Go version format")
83+
}
84+
i, err := strconv.Atoi(s[i+1:])
85+
return goVersion(i), err
86+
}
87+
88+
var testFile = template.Must(template.New("testFile").Funcs(map[string]interface{}{
89+
"rm2prom": func(d metrics.Description) string {
90+
ns, ss, n, ok := internal.RuntimeMetricsToProm(&d)
91+
if !ok {
92+
return ""
93+
}
94+
return prometheus.BuildFQName(ns, ss, n)
95+
},
96+
"nextVersion": func(version goVersion) string {
97+
return (version + goVersion(1)).String()
98+
},
99+
}).Parse(`// Code generated by gen_go_collector_metrics_set.go; DO NOT EDIT.
100+
//go:generate go run gen_go_collector_metrics_set.go {{.GoVersion}}
101+
102+
//go:build {{.GoVersion}} && !{{nextVersion .GoVersion}}
103+
// +build {{.GoVersion}},!{{nextVersion .GoVersion}}
104+
105+
package prometheus
106+
107+
var expectedRuntimeMetrics = map[string]string{
108+
{{- range .Descriptions -}}
109+
{{- $trans := rm2prom . -}}
110+
{{- if ne $trans "" }}
111+
{{.Name | printf "%q"}}: {{$trans | printf "%q"}},
112+
{{- end -}}
113+
{{end}}
114+
}
115+
`))

0 commit comments

Comments
 (0)