forked from gobench-io/gobench
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bench.go
321 lines (274 loc) · 6.91 KB
/
bench.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
package gobench
import (
"context"
"errors"
"fmt"
"log"
"sync"
"time"
"github.com/thoverik/gobench/ent"
"github.com/thoverik/gobench/metrics"
gometrics "github.com/rcrowley/go-metrics"
"github.com/thoverik/gobench/services/smtp"
)
var ErrIdNotFound = errors.New("id not found")
type benchStatus string
const (
statusInit benchStatus = "init"
statusRunning benchStatus = "running"
statusFinished benchStatus = "finished"
statusCancel benchStatus = "cancel"
)
type unit struct {
Title string // metric title
Type metrics.MetricType // to know the currnt unit type
metricID int // metric table foreign key
c gometrics.Counter
h gometrics.Histogram
g gometrics.Gauge
}
type Collect struct {
sync.Mutex
units map[string]unit
smtp smtp.Service
dbFilename string
name string
status benchStatus
createdAt time.Time
finishedAt time.Time
DB *ent.Client
}
var benchCollect Collect
func init() {
benchCollect = Collect{
units: make(map[string]unit),
status: statusInit,
createdAt: time.Now(),
}
}
// NewBench returns the singleton instance of the benchmark
func NewBench() *Collect {
return &benchCollect
}
// GetInstance returns the singleton instance of the benchmark
func GetInstance() *Collect {
return &benchCollect
}
// Setup starts the gobench program
// by creating a collect entity and database to store units
func Setup(groups []metrics.Group) error {
units := make(map[string]unit)
ctx := context.Background()
benchCollect.Lock()
defer benchCollect.Unlock()
for _, group := range groups {
// create new group if not existed
groupInst, created, err := bFindOrCreateGroup(ctx, benchCollect.DB, group)
if err != nil {
return fmt.Errorf("failed create group: %v", err)
}
// if the group is existed, continue
if !created {
continue
}
for _, graph := range group.Graphs {
// create new graph if not existed
graphInst, err := bCreateGraph(ctx, benchCollect.DB, graph, groupInst)
if err != nil {
return fmt.Errorf("failed create graph: %v", err)
}
for _, m := range graph.Metrics {
// create new metric if not existed
metricInstance, err := bFindOrCreateMetric(ctx, benchCollect.DB, m, graphInst)
if err != nil {
return fmt.Errorf("failed create metric: %v", err)
}
// create unit map
if m.Type == metrics.Counter {
c := gometrics.NewCounter()
if err := gometrics.Register(m.Title, c); err != nil {
if _, ok := err.(gometrics.DuplicateMetric); ok {
continue
}
return err
}
units[m.Title] = unit{
Title: m.Title,
Type: m.Type,
metricID: metricInstance.ID,
c: c,
}
}
if m.Type == metrics.Histogram {
s := gometrics.NewExpDecaySample(1028, 0.015)
h := gometrics.NewHistogram(s)
if err := gometrics.Register(m.Title, h); err != nil {
if _, ok := err.(gometrics.DuplicateMetric); ok {
continue
}
return err
}
units[m.Title] = unit{
Title: m.Title,
Type: m.Type,
metricID: metricInstance.ID,
h: h,
}
}
if m.Type == metrics.Gauge {
g := gometrics.NewGauge()
if err := gometrics.Register(m.Title, g); err != nil {
if _, ok := err.(gometrics.DuplicateMetric); ok {
continue
}
return err
}
units[m.Title] = unit{
Title: m.Title,
Type: m.Type,
metricID: metricInstance.ID,
g: g,
}
}
}
}
}
// aggregrate units
for k, v := range units {
benchCollect.units[k] = v
}
return nil
}
// Notify saves the id with value into metrics which later save to database
func Notify(title string, value int64) error {
u, ok := benchCollect.units[title]
if !ok {
log.Printf("error metric title %s not found\n", title)
return ErrIdNotFound
}
if u.Type == metrics.Counter {
u.c.Inc(value)
}
if u.Type == metrics.Histogram {
u.h.Update(value)
}
if u.Type == metrics.Gauge {
u.g.Update(value)
}
return nil
}
// Start function setup the db with benchCollect
// and begin to log metrics to db
func (c *Collect) Start() error {
log.Println("benchmark starting")
c.status = statusRunning
filename := time.Now().Format("2006-01-02-15-04-05") + ".sqlite3"
if err := c.setupDb(filename); err != nil {
return err
}
if err := c.createApplication(context.Background()); err != nil {
return err
}
c.handleSignals()
// log the metric in the background
go c.logScaled(5 * time.Second)
return nil
}
func (c *Collect) finish(s benchStatus) error {
log.Println("benchmark is shutting down")
c.status = s
c.finishedAt = time.Now()
if err := c.updateApplication(context.Background()); err != nil {
log.Printf("failed to update application %v\n", err)
}
if c.smtp.IsEnabled() {
if err := c.smtp.Send(smtp.Result{
Name: c.name,
CreatedAt: c.createdAt,
FinishedAt: c.finishedAt,
Status: string(c.status),
FilePath: c.dbFilename,
}); err != nil {
log.Printf("failed to send email %v\n", err)
}
}
return c.DB.Close()
}
// Finish closes the db connection
// and trigger services
func (c *Collect) Finish() error {
return c.finish(statusFinished)
}
func timestampMs() int64 {
return time.Now().UnixNano() / 1e6 // ms
}
func (c *Collect) logScaled(freq time.Duration) {
ch := make(chan interface{})
go func(channel chan interface{}) {
for range time.Tick(freq) {
channel <- struct{}{}
}
}(ch)
if err := c.logScaledOnCue(ch); err != nil {
log.Fatalln(err)
}
}
func (c *Collect) logScaledOnCue(ch chan interface{}) error {
units := c.units
ctx := context.Background()
for range ch {
now := timestampMs()
for _, u := range units {
switch u.Type {
case metrics.Counter:
_, err := c.DB.Counter.Create().
SetCount(u.c.Count()).
SetTime(now).
SetMetricID(u.metricID).
Save(ctx)
if err != nil {
return fmt.Errorf("failed create count: %v", err)
}
case metrics.Histogram:
h := u.h.Snapshot()
ps := u.h.Percentiles([]float64{0.5, 0.75, 0.95, 0.99, 0.999})
_, err := c.DB.Histogram.Create().
SetCount(h.Count()).
SetMin(h.Min()).
SetMax(h.Max()).
SetMean(h.Mean()).
SetStddev(h.StdDev()).
SetMedian(ps[0]).
SetP75(ps[1]).
SetP95(ps[2]).
SetP99(ps[3]).
SetP999(ps[4]).
SetTime(now).
SetMetricID(u.metricID).
Save(ctx)
if err != nil {
return fmt.Errorf("failed creating count: %v", err)
}
case metrics.Gauge:
_, err := c.DB.Gauge.Create().
SetValue(u.g.Value()).
SetTime(now).
SetMetricID(u.metricID).
Save(ctx)
if err != nil {
return fmt.Errorf("failed creating gauge: %v", err)
}
}
}
}
return nil
}
// Email sets the smtp service configuration
func (c *Collect) Email(config smtp.Config) *Collect {
c.smtp = smtp.NewService(config)
return c
}
func (c *Collect) Name(name string) *Collect {
c.name = name
return c
}