-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
237 lines (199 loc) · 5.04 KB
/
main.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
package main
import (
"bytes"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"unicode"
"unicode/utf8"
"github.com/hexdigest/gowrap/generator"
"github.com/pkg/errors"
)
const version = "1.3"
type (
interfaceInfo struct {
Name string
Package string
OutputFile string
}
)
func main() {
interfaces := processFlags()
for _, iface := range interfaces {
opts := generator.Options{
InterfaceName: iface.Name,
SourcePackage: iface.Package,
OutputFile: iface.OutputFile,
HeaderTemplate: headerTemplate,
BodyTemplate: bodyTemplate,
Vars: map[string]interface{}{
"DecoratorName": iface.Name + "Metrics",
},
HeaderVars: map[string]interface{}{
"Version": version,
},
}
if err := generate(opts); err != nil {
die("failed to generate %s: %v", opts.OutputFile, err)
}
fmt.Printf("Generated file: %s\n", opts.OutputFile)
}
}
func generate(o generator.Options) error {
g, err := generator.NewGenerator(o)
if err != nil {
return err
}
buf := bytes.NewBuffer([]byte{})
if err = g.Generate(buf); err != nil {
return errors.Wrap(err, "failed to generate decorator")
}
return ioutil.WriteFile(o.OutputFile, buf.Bytes(), 0644)
}
const (
headerTemplate = `
package {{$.Package.Name}}
// Code generated by http://github.com/gojuno/metricsgen ({{$.Options.HeaderVars.Version}}). DO NOT EDIT.
`
bodyTemplate = `
import (
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
)
{{ $decorator := .Vars.DecoratorName }}
// {{$decorator}} implements {{.Interface.Type}} interface with all methods wrapped
// with Prometheus metrics
type {{$decorator}} struct {
base {{.Interface.Type}}
instanceName string
summary *prometheus.SummaryVec
}
func (_d {{$decorator}}) _observe(method string, startedAt time.Time) {
duration := time.Since(startedAt)
_d.summary.WithLabelValues(_d.instanceName, method).Observe(duration.Seconds())
}
func New{{$decorator}}Summary(metricName string) *prometheus.SummaryVec {
sv := prometheus.NewSummaryVec(
prometheus.SummaryOpts{
Name: metricName,
Help: metricName,
},
[]string{"instance_name", "method"},
)
prometheus.MustRegister(sv)
return sv
}
// New{{$decorator}}WithSummary returns an instance of the {{.Interface.Type}} decorated with prometheus summary metric
func New{{$decorator}}WithSummary(base {{.Interface.Type}}, instanceName string, sv *prometheus.SummaryVec) {{$decorator}} {
return {{$decorator}} {
base: base,
instanceName: instanceName,
summary: sv,
}
}
{{range $method := .Interface.Methods}}
// {{$method.Name}} implements {{$.Interface.Type}}
func (_d {{$decorator}}) {{$method.Declaration}} {
defer _d._observe("{{$method.Name}}", time.Now())
{{$method.Pass "_d.base."}}
}
{{end}}
`
)
func processFlags() []interfaceInfo {
var (
help = flag.Bool("h", false, "show this help message")
interfaces = flag.String("i", "", "comma-separated names of interfaces to wrap, i.e fmt.Stringer,io.Reader, use io.* notation to generate metric decorators for all interfaces in an io package")
output = flag.String("o", "", "directory to place generated files to")
suffix = flag.String("s", "_metrics.go", "output file name suffix which is added to file names when multiple interfaces are given")
v = flag.Bool("version", false, "show metricsgen version")
)
flag.Parse()
if *help {
flag.Usage()
os.Exit(0)
}
if *v {
fmt.Printf("metricsgen version: %s\n", version)
os.Exit(0)
}
if *interfaces == "" {
die("missing required parameter: -i, use -h flag for help")
}
if *output == "" {
die("missing required parameter: -o, use -h flag for help")
}
result := []interfaceInfo{}
for _, i := range strings.Split(*interfaces, ",") {
chunks := strings.Split(i, ".")
if len(chunks) < 2 {
die("invalid interface name: %s\nname should be in the form <import path>.<interface type>, i.e. io.Reader\n", i)
}
interfaceName := chunks[len(chunks)-1]
result = append(result, interfaceInfo{
Name: interfaceName,
Package: strings.Join(chunks[0:len(chunks)-1], "."),
OutputFile: filepath.Join(*output, camelToSnake(interfaceName)+*suffix),
})
}
return result
}
func camelToSnake(s string) string {
b := buffer{
r: make([]byte, 0, len(s)),
}
var m rune
var w bool
for _, ch := range s {
if unicode.IsUpper(ch) {
if m != 0 {
if !w {
b.indent()
w = true
}
b.write(m)
}
m = unicode.ToLower(ch)
} else {
if m != 0 {
b.indent()
b.write(m)
m = 0
w = false
}
b.write(ch)
}
}
if m != 0 {
if !w {
b.indent()
}
b.write(m)
}
return string(b.r)
}
type buffer struct {
r []byte
runeBytes [utf8.UTFMax]byte
}
func (b *buffer) write(r rune) {
if r < utf8.RuneSelf {
b.r = append(b.r, byte(r))
return
}
n := utf8.EncodeRune(b.runeBytes[0:], r)
b.r = append(b.r, b.runeBytes[0:n]...)
}
func (b *buffer) indent() {
if len(b.r) > 0 {
b.r = append(b.r, '_')
}
}
func die(format string, args ...interface{}) {
fmt.Fprintf(os.Stderr, "metricsgen: "+format+"\n", args...)
os.Exit(1)
}