File: gen_go_collector_set.go

package info (click to toggle)
golang-github-prometheus-client-golang 1.23.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, forky, sid
  • size: 3,192 kB
  • sloc: makefile: 68; ansic: 46; sh: 21
file content (238 lines) | stat: -rw-r--r-- 6,597 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// Copyright 2021 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 ignore
// +build ignore

package main

import (
	"bytes"
	"fmt"
	"go/format"
	"log"
	"os"
	"regexp"
	"runtime"
	"runtime/metrics"
	"sort"
	"strings"
	"text/template"

	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/internal"

	version "github.com/hashicorp/go-version"
)

type metricGroup struct {
	Name    string
	Regex   *regexp.Regexp
	Metrics []string
}

var metricGroups = []metricGroup{
	{"withAllMetrics", nil, nil},
	{"withGCMetrics", regexp.MustCompile("^go_gc_.*"), nil},
	{"withMemoryMetrics", regexp.MustCompile("^go_memory_classes_.*"), nil},
	{"withSchedulerMetrics", regexp.MustCompile("^go_sched_.*"), nil},
	{"withDebugMetrics", regexp.MustCompile("^go_godebug_non_default_behavior_.*"), nil},
}

func main() {
	var givenVersion string
	toolVersion := runtime.Version()
	if len(os.Args) != 2 {
		log.Printf("requires Go version (e.g. go1.17) as an argument. Since it is not specified, assuming %s.", toolVersion)
		givenVersion = toolVersion
	} else {
		givenVersion = os.Args[1]
	}
	log.Printf("given version for Go: %s", givenVersion)
	log.Printf("tool version for Go: %s", toolVersion)

	tv, err := version.NewVersion(strings.TrimPrefix(givenVersion, "go"))
	if err != nil {
		log.Fatal(err)
	}

	toolVersion = strings.Split(strings.TrimPrefix(toolVersion, "go"), " ")[0]
	gv, err := version.NewVersion(toolVersion)
	if err != nil {
		log.Fatal(err)
	}
	if !gv.Equal(tv) {
		log.Fatalf("using Go version %q but expected Go version %q", tv, gv)
	}

	v := goVersion(gv.Segments()[1])
	log.Printf("generating metrics for Go version %q", v)

	descriptions := computeMetricsList(metrics.All())
	groupedMetrics := groupMetrics(descriptions)

	// Find default metrics.
	var defaultRuntimeDesc []metrics.Description
	for _, d := range metrics.All() {
		if !internal.GoCollectorDefaultRuntimeMetrics.MatchString(d.Name) {
			continue
		}
		defaultRuntimeDesc = append(defaultRuntimeDesc, d)
	}

	defaultRuntimeMetricsList := computeMetricsList(defaultRuntimeDesc)

	onlyGCDefRuntimeMetricsList := []string{}
	onlySchedDefRuntimeMetricsList := []string{}

	for _, m := range defaultRuntimeMetricsList {
		if strings.HasPrefix(m, "go_gc") {
			onlyGCDefRuntimeMetricsList = append(onlyGCDefRuntimeMetricsList, m)
		}
		if strings.HasPrefix(m, "go_sched") {
			onlySchedDefRuntimeMetricsList = append(onlySchedDefRuntimeMetricsList, m)
		} else {
			continue
		}
	}

	// Generate code.
	var buf bytes.Buffer
	err = testFile.Execute(&buf, struct {
		GoVersion                      goVersion
		Groups                         []metricGroup
		DefaultRuntimeMetricsList      []string
		OnlyGCDefRuntimeMetricsList    []string
		OnlySchedDefRuntimeMetricsList []string
	}{
		GoVersion:                      v,
		Groups:                         groupedMetrics,
		DefaultRuntimeMetricsList:      defaultRuntimeMetricsList,
		OnlyGCDefRuntimeMetricsList:    onlyGCDefRuntimeMetricsList,
		OnlySchedDefRuntimeMetricsList: onlySchedDefRuntimeMetricsList,
	})
	if err != nil {
		log.Fatalf("executing template: %v", err)
	}

	// Format it.
	result, err := format.Source(buf.Bytes())
	if err != nil {
		log.Fatalf("formatting code: %v", err)
	}

	// Write it to a file.
	fname := fmt.Sprintf("go_collector_%s_test.go", v.Abbr())
	if err := os.WriteFile(fname, result, 0o644); err != nil {
		log.Fatalf("writing file: %v", err)
	}
}

func computeMetricsList(descs []metrics.Description) []string {
	var metricsList []string
	for _, d := range descs {
		if trans := rm2prom(d); trans != "" {
			metricsList = append(metricsList, trans)
		}
	}
	return metricsList
}

func rm2prom(d metrics.Description) string {
	ns, ss, n, ok := internal.RuntimeMetricsToProm(&d)
	if !ok {
		return ""
	}
	return prometheus.BuildFQName(ns, ss, n)
}

func groupMetrics(metricsList []string) []metricGroup {
	var groupedMetrics []metricGroup
	for _, group := range metricGroups {
		matchedMetrics := make([]string, 0)
		for _, metric := range metricsList {
			if group.Regex == nil || group.Regex.MatchString(metric) {
				matchedMetrics = append(matchedMetrics, metric)
			}
		}

		sort.Strings(matchedMetrics)
		groupedMetrics = append(groupedMetrics, metricGroup{
			Name:    group.Name,
			Regex:   group.Regex,
			Metrics: matchedMetrics,
		})
	}
	return groupedMetrics
}

type goVersion int

func (g goVersion) String() string {
	return fmt.Sprintf("go1.%d", g)
}

func (g goVersion) Abbr() string {
	return fmt.Sprintf("go1%d", g)
}

var testFile = template.Must(template.New("testFile").Funcs(map[string]interface{}{
	"nextVersion": func(version goVersion) string {
		return (version + goVersion(1)).String()
	},
}).Parse(`// Copyright 2022 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 {{.GoVersion}} && !{{nextVersion .GoVersion}}
// +build {{.GoVersion}},!{{nextVersion .GoVersion}}

package collectors

{{- range .Groups }}
func {{ .Name }}() []string {
	return withBaseMetrics([]string{
		{{- range $metric := .Metrics }}
			{{ $metric | printf "%q" }},
		{{- end }}
	})
}
{{ end }}

var (
	defaultRuntimeMetrics = []string{
		{{- range $metric := .DefaultRuntimeMetricsList }}
			{{ $metric | printf "%q"}},
		{{- end }}
	}
	onlyGCDefRuntimeMetrics = []string{
		{{- range $metric := .OnlyGCDefRuntimeMetricsList }}
			{{ $metric | printf "%q"}},
		{{- end }}
	}
	onlySchedDefRuntimeMetrics = []string{
		{{- range $metric := .OnlySchedDefRuntimeMetricsList }}
			{{ $metric | printf "%q"}},
		{{- end }}
	}
)
`))