-
Notifications
You must be signed in to change notification settings - Fork 11
/
metricsgen.go
347 lines (313 loc) · 8.44 KB
/
metricsgen.go
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// metricsgen is a code generation tool for creating constructors for Tendermint
// metrics types.
package main
import (
"bytes"
"flag"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"go/types"
"io"
"io/fs"
"log"
"os"
"path"
"path/filepath"
"reflect"
"regexp"
"strconv"
"strings"
"text/template"
)
func init() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, `Usage: %[1]s -struct <struct>
Generate constructors for the metrics type specified by -struct contained in
the current directory. The tool creates a new file in the current directory
containing the generated code.
Options:
`, filepath.Base(os.Args[0]))
flag.PrintDefaults()
}
}
const metricsPackageName = "github.com/go-kit/kit/metrics"
const (
metricNameTag = "metrics_name"
labelsTag = "metrics_labels"
bucketTypeTag = "metrics_buckettype"
bucketSizeTag = "metrics_bucketsizes"
)
var (
dir = flag.String("dir", ".", "Path to the directory containing the target package")
strct = flag.String("struct", "Metrics", "Struct to parse for metrics")
)
var bucketType = map[string]string{
"exprange": "stdprometheus.ExponentialBucketsRange",
"exp": "stdprometheus.ExponentialBuckets",
"lin": "stdprometheus.LinearBuckets",
}
var tmpl = template.Must(template.New("tmpl").Parse(`// Code generated by metricsgen. DO NOT EDIT.
package {{ .Package }}
import (
"github.com/go-kit/kit/metrics/discard"
prometheus "github.com/go-kit/kit/metrics/prometheus"
stdprometheus "github.com/prometheus/client_golang/prometheus"
)
func PrometheusMetrics(namespace string, labelsAndValues...string) *Metrics {
labels := []string{}
for i := 0; i < len(labelsAndValues); i += 2 {
labels = append(labels, labelsAndValues[i])
}
return &Metrics{
{{ range $metric := .ParsedMetrics }}
{{- $metric.FieldName }}: prometheus.New{{ $metric.TypeName }}From(stdprometheus.{{$metric.TypeName }}Opts{
Namespace: namespace,
Subsystem: MetricsSubsystem,
Name: "{{$metric.MetricName }}",
Help: "{{ $metric.Description }}",
{{ if ne $metric.HistogramOptions.BucketType "" }}
Buckets: {{ $metric.HistogramOptions.BucketType }}({{ $metric.HistogramOptions.BucketSizes }}),
{{ else if ne $metric.HistogramOptions.BucketSizes "" }}
Buckets: []float64{ {{ $metric.HistogramOptions.BucketSizes }} },
{{ end }}
{{- if eq (len $metric.Labels) 0 }}
}, labels).With(labelsAndValues...),
{{ else }}
}, append(labels, {{$metric.Labels}})).With(labelsAndValues...),
{{ end }}
{{- end }}
}
}
func NopMetrics() *Metrics {
return &Metrics{
{{- range $metric := .ParsedMetrics }}
{{ $metric.FieldName }}: discard.New{{ $metric.TypeName }}(),
{{- end }}
}
}
`))
// ParsedMetricField is the data parsed for a single field of a metric struct.
type ParsedMetricField struct {
TypeName string
FieldName string
MetricName string
Description string
Labels string
HistogramOptions HistogramOpts
}
type HistogramOpts struct {
BucketType string
BucketSizes string
}
// TemplateData is all of the data required for rendering a metric file template.
type TemplateData struct {
Package string
ParsedMetrics []ParsedMetricField
}
func main() {
flag.Parse()
if *strct == "" {
log.Fatal("You must specify a non-empty -struct")
}
td, err := ParseMetricsDir(".", *strct)
if err != nil {
log.Fatalf("Parsing file: %v", err)
}
out := filepath.Join(*dir, "metrics.gen.go")
f, err := os.Create(out)
if err != nil {
log.Fatalf("Opening file: %v", err)
}
err = GenerateMetricsFile(f, td)
if err != nil {
log.Fatalf("Generating code: %v", err)
}
}
func ignoreTestFiles(f fs.FileInfo) bool {
return !strings.Contains(f.Name(), "_test.go")
}
// ParseMetricsDir parses the dir and scans for a struct matching structName,
// ignoring all test files. ParseMetricsDir iterates the fields of the metrics
// struct and builds a TemplateData using the data obtained from the abstract syntax tree.
func ParseMetricsDir(dir string, structName string) (TemplateData, error) {
fs := token.NewFileSet()
d, err := parser.ParseDir(fs, dir, ignoreTestFiles, parser.ParseComments)
if err != nil {
return TemplateData{}, err
}
if len(d) > 1 {
return TemplateData{}, fmt.Errorf("multiple packages found in %s", dir)
}
if len(d) == 0 {
return TemplateData{}, fmt.Errorf("no go pacakges found in %s", dir)
}
// Grab the package name.
var pkgName string
var pkg *ast.Package
for pkgName, pkg = range d {
}
td := TemplateData{
Package: pkgName,
}
// Grab the metrics struct
m, mPkgName, err := findMetricsStruct(pkg.Files, structName)
if err != nil {
return TemplateData{}, err
}
for _, f := range m.Fields.List {
if !isMetric(f.Type, mPkgName) {
continue
}
pmf := parseMetricField(f)
td.ParsedMetrics = append(td.ParsedMetrics, pmf)
}
return td, err
}
// GenerateMetricsFile executes the metrics file template, writing the result
// into the io.Writer.
func GenerateMetricsFile(w io.Writer, td TemplateData) error {
b := []byte{}
buf := bytes.NewBuffer(b)
err := tmpl.Execute(buf, td)
if err != nil {
return err
}
b, err = format.Source(buf.Bytes())
if err != nil {
return err
}
_, err = io.Copy(w, bytes.NewBuffer(b))
if err != nil {
return err
}
return nil
}
func findMetricsStruct(files map[string]*ast.File, structName string) (*ast.StructType, string, error) {
var (
st *ast.StructType
)
for _, file := range files {
mPkgName, err := extractMetricsPackageName(file.Imports)
if err != nil {
return nil, "", fmt.Errorf("unable to determine metrics package name: %v", err)
}
if !ast.FilterFile(file, func(name string) bool {
return name == structName
}) {
continue
}
ast.Inspect(file, func(n ast.Node) bool {
switch f := n.(type) {
case *ast.TypeSpec:
if f.Name.Name == structName {
var ok bool
st, ok = f.Type.(*ast.StructType)
if !ok {
err = fmt.Errorf("found identifier for %q of wrong type", structName)
}
}
return false
default:
return true
}
})
if err != nil {
return nil, "", err
}
if st != nil {
return st, mPkgName, nil
}
}
return nil, "", fmt.Errorf("target struct %q not found in dir", structName)
}
func parseMetricField(f *ast.Field) ParsedMetricField {
pmf := ParsedMetricField{
Description: extractHelpMessage(f.Doc),
MetricName: extractFieldName(f.Names[0].String(), f.Tag),
FieldName: f.Names[0].String(),
TypeName: extractTypeName(f.Type),
Labels: extractLabels(f.Tag),
}
if pmf.TypeName == "Histogram" {
pmf.HistogramOptions = extractHistogramOptions(f.Tag)
}
return pmf
}
func extractTypeName(e ast.Expr) string {
return strings.TrimPrefix(path.Ext(types.ExprString(e)), ".")
}
func extractHelpMessage(cg *ast.CommentGroup) string {
if cg == nil {
return ""
}
var help []string //nolint: prealloc
for _, c := range cg.List {
mt := strings.TrimPrefix(c.Text, "//metrics:")
if mt != c.Text {
return strings.TrimSpace(mt)
}
help = append(help, strings.TrimSpace(strings.TrimPrefix(c.Text, "//")))
}
return strings.Join(help, " ")
}
func isMetric(e ast.Expr, mPkgName string) bool {
return strings.Contains(types.ExprString(e), fmt.Sprintf("%s.", mPkgName))
}
func extractLabels(bl *ast.BasicLit) string {
if bl != nil {
t := reflect.StructTag(strings.Trim(bl.Value, "`"))
if v := t.Get(labelsTag); v != "" {
var res []string
for _, s := range strings.Split(v, ",") {
res = append(res, strconv.Quote(strings.TrimSpace(s)))
}
return strings.Join(res, ",")
}
}
return ""
}
func extractFieldName(name string, tag *ast.BasicLit) string {
if tag != nil {
t := reflect.StructTag(strings.Trim(tag.Value, "`"))
if v := t.Get(metricNameTag); v != "" {
return v
}
}
return toSnakeCase(name)
}
func extractHistogramOptions(tag *ast.BasicLit) HistogramOpts {
h := HistogramOpts{}
if tag != nil {
t := reflect.StructTag(strings.Trim(tag.Value, "`"))
if v := t.Get(bucketTypeTag); v != "" {
h.BucketType = bucketType[v]
}
if v := t.Get(bucketSizeTag); v != "" {
h.BucketSizes = v
}
}
return h
}
func extractMetricsPackageName(imports []*ast.ImportSpec) (string, error) {
for _, i := range imports {
u, err := strconv.Unquote(i.Path.Value)
if err != nil {
return "", err
}
if u == metricsPackageName {
if i.Name != nil {
return i.Name.Name, nil
}
return path.Base(u), nil
}
}
return "", nil
}
var capitalChange = regexp.MustCompile("([a-z0-9])([A-Z])")
func toSnakeCase(str string) string {
snake := capitalChange.ReplaceAllString(str, "${1}_${2}")
return strings.ToLower(snake)
}