-
Notifications
You must be signed in to change notification settings - Fork 12
/
registry.go
408 lines (338 loc) · 11.5 KB
/
registry.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
package poplar
import (
"context"
"io"
"os"
"path/filepath"
"sync"
"testing"
"time"
"github.com/mongodb/ftdc"
"github.com/mongodb/ftdc/events"
"github.com/pkg/errors"
)
// RecorderType represents the underlying recorder type.
type RecorderType string
const (
RecorderPerf RecorderType = "perf"
RecorderPerfSingle = "perf-single"
RecorderPerf100ms = "perf-grouped-100ms"
RecorderPerf1s = "perf-grouped-1s"
RecorderHistogramSingle = "histogram-single"
RecorderHistogram100ms = "histogram-grouped-100ms"
RecorderHistogram1s = "histogram-grouped-1s"
CustomMetrics = "custom"
)
// EventsCollectorType represents the collector strategy for events
// collector.
type EventsCollectorType string
const (
EventsCollectorBasic EventsCollectorType = "basic"
EventsCollectorPassthrough = "passthrough"
EventsCollectorSampling100 = "sampling-100"
EventsCollectorSampling1k = "sampling-1k"
EventsCollectorSampling10k = "sampling-10k"
EventsCollectorSampling100k = "sampling-100k"
EventsCollectorRandomSampling50 = "rand-sampling-50"
EventsCollectorRandomSampling25 = "rand-sampling-25"
EventsCollectorRandomSampling10 = "rand-sampling-10"
EventsCollectorInterval100ms = "interval-100ms"
EventsCollectorInterval1s = "interval-1s"
)
// Validate the underlying recorder type.
func (t RecorderType) Validate() error {
switch t {
case RecorderPerf, RecorderPerfSingle, RecorderPerf100ms, RecorderPerf1s,
RecorderHistogramSingle, RecorderHistogram100ms, RecorderHistogram1s, CustomMetrics:
return nil
default:
return errors.Errorf("%s is not a supported recorder type", t)
}
}
// Validate the underlying events collector type.
func (t EventsCollectorType) Validate() error {
switch t {
case EventsCollectorBasic, EventsCollectorInterval100ms, EventsCollectorInterval1s,
EventsCollectorPassthrough, EventsCollectorRandomSampling10, EventsCollectorRandomSampling25,
EventsCollectorRandomSampling50, EventsCollectorSampling100, EventsCollectorSampling100k, EventsCollectorSampling10k, EventsCollectorSampling1k:
return nil
default:
return errors.Errorf("%s is not a supported events collector type", t)
}
}
type recorderInstance struct {
file io.WriteCloser
collector ftdc.Collector
recorder events.Recorder
eventsCollector events.Collector
tracker *customEventTracker
ctx context.Context
cancel context.CancelFunc
isDynamic bool
isCustom bool
isEvents bool
}
type customEventTracker struct {
events.Custom
sync.Mutex
}
func (c *customEventTracker) Add(key string, value interface{}) error {
if c == nil {
return errors.New("tracker is not populated")
}
c.Lock()
defer c.Unlock()
return errors.WithStack(c.Custom.Add(key, value))
}
func (c *customEventTracker) Reset() {
c.Lock()
defer c.Unlock()
c.Custom = events.MakeCustom(cap(c.Custom))
}
func (c *customEventTracker) Dump() events.Custom {
c.Lock()
defer c.Unlock()
return c.Custom
}
// CustomMetricsCollector defines an interface for collecting metrics.
type CustomMetricsCollector interface {
Add(string, interface{}) error
Dump() events.Custom
Reset()
}
// RecorderRegistry caches instances of recorders.
type RecorderRegistry struct {
cache map[string]*recorderInstance
benchPrefix string
mu sync.Mutex
}
// NewRegistry returns a new (empty) RecorderRegistry.
func NewRegistry() *RecorderRegistry {
return &RecorderRegistry{
cache: map[string]*recorderInstance{},
}
}
// Create builds a new collector, of the given name with the specified
// options controlling the collector type and configuration.
//
// If the options specify a filename that already exists, then Create
// will return an error.
func (r *RecorderRegistry) Create(key string, collOpts CreateOptions) (events.Recorder, error) {
r.mu.Lock()
defer r.mu.Unlock()
_, ok := r.cache[key]
if ok {
return nil, errors.Errorf("a recorder named '%s' already exists", key)
}
instance, err := collOpts.build()
if err != nil {
return nil, errors.Wrap(err, "constructing recorder output")
}
r.cache[key] = instance
return instance.recorder, nil
}
// GetRecorder returns the Recorder instance for this key. Returns
// false when the recorder does not exist.
func (r *RecorderRegistry) GetRecorder(key string) (events.Recorder, bool) {
r.mu.Lock()
defer r.mu.Unlock()
impl, ok := r.cache[key]
if !ok {
return nil, false
}
return impl.recorder, true
}
// GetCustomCollector returns the CustomMetricsCollector instance for this key.
// Returns false when the collector does not exist.
func (r *RecorderRegistry) GetCustomCollector(key string) (CustomMetricsCollector, bool) {
r.mu.Lock()
defer r.mu.Unlock()
impl, ok := r.cache[key]
if !ok {
return nil, false
}
if !impl.isCustom || impl.tracker == nil {
return nil, false
}
return impl.tracker, true
}
// GetCollector returns the collector instance for this key. Will
// return false, when the collector does not exist OR if the collector
// is not dynamic.
func (r *RecorderRegistry) GetCollector(key string) (ftdc.Collector, bool) {
r.mu.Lock()
defer r.mu.Unlock()
impl, ok := r.cache[key]
if !ok {
return nil, false
}
if !impl.isDynamic || impl.collector == nil {
return nil, false
}
return impl.collector, true
}
// GetEventsCollector returns the events.Collector instance for this
// key. Will return false, when the collector does not exist OR if the collector
// is not an events.Collector.
func (r *RecorderRegistry) GetEventsCollector(key string) (events.Collector, bool) {
r.mu.Lock()
defer r.mu.Unlock()
impl, ok := r.cache[key]
if !ok {
return nil, false
}
if !impl.isEvents || impl.eventsCollector == nil {
return nil, false
}
return impl.eventsCollector, true
}
// SetBenchRecorderPrefix sets the bench prefix for this registry.
func (r *RecorderRegistry) SetBenchRecorderPrefix(prefix string) {
r.mu.Lock()
defer r.mu.Unlock()
r.benchPrefix = prefix
}
// MakeBenchmark configures a recorder to support executing a
// BenchmarkCase in the form of a standard library benchmarking
// format.
func (r *RecorderRegistry) MakeBenchmark(bench *BenchmarkCase) (func(*testing.B), func() error) {
name := bench.Name()
r.mu.Lock()
fqname := filepath.Join(r.benchPrefix, name) + ".ftdc"
r.mu.Unlock()
recorder, err := r.Create(name, CreateOptions{
Path: fqname,
ChunkSize: 1024,
Streaming: true,
Dynamic: false,
Recorder: bench.Recorder,
})
if err != nil {
return func(b *testing.B) { b.Fatal(errors.Wrap(err, "making recorder")) },
func() error { return nil }
}
return bench.Bench.standard(recorder), func() error { return r.Close(name) }
}
// Close flushes and closes the underlying recorder and collector and
// then removes it from the cache.
func (r *RecorderRegistry) Close(key string) error {
r.mu.Lock()
defer r.mu.Unlock()
if impl, ok := r.cache[key]; ok {
if impl.isEvents {
impl.cancel()
time.Sleep(100 * time.Millisecond)
}
if impl.isCustom {
if err := impl.collector.Add(impl.tracker.Custom); err != nil {
return errors.Wrap(err, "flushing interval summarizations")
}
} else {
if err := impl.recorder.EndTest(); err != nil {
return errors.Wrap(err, "flushing recorder")
}
}
if err := ftdc.FlushCollector(impl.collector, impl.file); err != nil {
return errors.Wrap(err, "writing collector contents to file")
}
if err := impl.file.Close(); err != nil {
return errors.Wrap(err, "closing open file")
}
}
delete(r.cache, key)
return nil
}
// CreateOptions support the use and creation of a collector.
type CreateOptions struct {
Path string
ChunkSize int
Streaming bool
Dynamic bool
Buffered bool
Recorder RecorderType
Events EventsCollectorType
}
func (opts *CreateOptions) build() (*recorderInstance, error) {
if err := opts.Recorder.Validate(); err != nil {
return nil, errors.Wrap(err, "invalid recorder type")
}
if opts.Recorder == CustomMetrics && !opts.Dynamic {
return nil, errors.New("cannot use the custom metrics collector with a non-dynamic collector")
}
if _, err := os.Stat(opts.Path); !os.IsNotExist(err) {
return nil, errors.Errorf("file '%s' already exists", opts.Path)
}
file, err := os.Create(opts.Path)
if err != nil {
return nil, errors.Wrapf(err, "opening file '%s'", opts.Path)
}
out := &recorderInstance{
isDynamic: opts.Dynamic,
file: file,
isEvents: opts.Events != "",
}
out.ctx, out.cancel = context.WithCancel(context.Background())
switch {
case opts.Streaming && opts.Dynamic:
out.collector = ftdc.NewStreamingDynamicCollector(opts.ChunkSize, file)
case !opts.Streaming && opts.Dynamic:
out.collector = ftdc.NewDynamicCollector(opts.ChunkSize)
case opts.Streaming && !opts.Dynamic:
out.collector = ftdc.NewStreamingCollector(opts.ChunkSize, file)
case !opts.Streaming && !opts.Dynamic:
out.collector = ftdc.NewBatchCollector(opts.ChunkSize)
default:
return nil, errors.New("invalid collector defined")
}
if opts.Buffered {
out.collector = ftdc.NewBufferedCollector(out.ctx, 4*opts.ChunkSize, out.collector)
}
out.collector = ftdc.NewSynchronizedCollector(out.collector)
switch opts.Events {
case EventsCollectorBasic:
out.eventsCollector = events.NewBasicCollector(out.collector)
case EventsCollectorPassthrough:
out.eventsCollector = events.NewPassthroughCollector(out.collector)
case EventsCollectorSampling100:
out.eventsCollector = events.NewSamplingCollector(out.collector, 100)
case EventsCollectorSampling1k:
out.eventsCollector = events.NewSamplingCollector(out.collector, 1000)
case EventsCollectorSampling10k:
out.eventsCollector = events.NewSamplingCollector(out.collector, 10000)
case EventsCollectorSampling100k:
out.eventsCollector = events.NewSamplingCollector(out.collector, 100000)
case EventsCollectorRandomSampling50:
out.eventsCollector = events.NewRandomSamplingCollector(out.collector, true, 50)
case EventsCollectorRandomSampling25:
out.eventsCollector = events.NewRandomSamplingCollector(out.collector, true, 25)
case EventsCollectorRandomSampling10:
out.eventsCollector = events.NewRandomSamplingCollector(out.collector, true, 10)
case EventsCollectorInterval100ms:
out.eventsCollector = events.NewIntervalCollector(out.collector, 100*time.Millisecond)
case EventsCollectorInterval1s:
out.eventsCollector = events.NewIntervalCollector(out.collector, time.Second)
}
out.eventsCollector = events.NewSynchronizedCollector(out.eventsCollector)
switch opts.Recorder {
case RecorderPerf:
out.recorder = events.NewRawRecorder(out.collector)
case RecorderPerfSingle:
out.recorder = events.NewSingleRecorder(out.collector)
case RecorderPerf100ms:
out.recorder = events.NewGroupedRecorder(out.collector, 100*time.Millisecond)
case RecorderPerf1s:
out.recorder = events.NewGroupedRecorder(out.collector, time.Second)
case RecorderHistogramSingle:
out.recorder = events.NewSingleHistogramRecorder(out.collector)
case RecorderHistogram100ms:
out.recorder = events.NewHistogramGroupedRecorder(out.collector, 100*time.Millisecond)
case RecorderHistogram1s:
out.recorder = events.NewHistogramGroupedRecorder(out.collector, time.Second)
case CustomMetrics:
out.isCustom = true
out.tracker = &customEventTracker{Custom: events.MakeCustom(128)}
default:
return nil, errors.New("invalid recorder defined")
}
return out, nil
}