-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathwrapper.go
439 lines (375 loc) · 12.5 KB
/
wrapper.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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you 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.
package module
import (
"context"
"fmt"
"math/rand"
"sync"
"time"
"github.com/elastic/beats/v7/libbeat/beat"
"github.com/elastic/beats/v7/libbeat/common"
"github.com/elastic/beats/v7/libbeat/logp"
"github.com/elastic/beats/v7/libbeat/monitoring"
"github.com/elastic/beats/v7/libbeat/testing"
"github.com/elastic/beats/v7/metricbeat/mb"
)
// Expvar metric names.
const (
successesKey = "success"
failuresKey = "failures"
eventsKey = "events"
)
var (
debugf = logp.MakeDebug("module")
fetchesLock = sync.Mutex{}
fetches = map[string]*stats{}
)
// Wrapper contains the Module and the private data associated with
// running the Module and its MetricSets.
//
// Use NewWrapper or NewWrappers to construct new Wrappers.
type Wrapper struct {
mb.Module
metricSets []*metricSetWrapper // List of pointers to its associated MetricSets.
// Options
maxStartDelay time.Duration
eventModifiers []mb.EventModifier
}
// metricSetWrapper contains the MetricSet and the private data associated with
// running the MetricSet. It contains a pointer to the parent Module.
type metricSetWrapper struct {
mb.MetricSet
module *Wrapper // Parent Module.
stats *stats // stats for this MetricSet.
periodic bool // Set to true if this metricset is a periodic fetcher
}
// stats bundles common metricset stats.
type stats struct {
key string // full stats key
ref uint32 // number of modules/metricsets reusing stats instance
success *monitoring.Int // Total success events.
failures *monitoring.Int // Total error events.
events *monitoring.Int // Total events published.
}
// NewWrapper creates a new module and its associated metricsets based on the given configuration.
func NewWrapper(config *common.Config, r *mb.Register, options ...Option) (*Wrapper, error) {
module, metricSets, err := mb.NewModule(config, r)
if err != nil {
return nil, err
}
return createWrapper(module, metricSets, options...)
}
// NewWrapperForMetricSet creates a wrapper for the selected module and metricset.
func NewWrapperForMetricSet(module mb.Module, metricSet mb.MetricSet, options ...Option) (*Wrapper, error) {
return createWrapper(module, []mb.MetricSet{metricSet}, options...)
}
func createWrapper(module mb.Module, metricSets []mb.MetricSet, options ...Option) (*Wrapper, error) {
wrapper := &Wrapper{
Module: module,
metricSets: make([]*metricSetWrapper, len(metricSets)),
}
for _, applyOption := range options {
applyOption(wrapper)
}
for i, metricSet := range metricSets {
wrapper.metricSets[i] = &metricSetWrapper{
MetricSet: metricSet,
module: wrapper,
stats: getMetricSetStats(wrapper.Name(), metricSet.Name()),
}
}
return wrapper, nil
}
// Wrapper methods
// Start starts the Module's MetricSet workers which are responsible for
// fetching metrics. The workers will continue to periodically fetch until the
// done channel is closed. When the done channel is closed all MetricSet workers
// will stop and the returned output channel will be closed.
//
// The returned channel is buffered with a length one one. It must drained to
// prevent blocking the operation of the MetricSets.
//
// Start should be called only once in the life of a Wrapper.
func (mw *Wrapper) Start(done <-chan struct{}) <-chan beat.Event {
debugf("Starting %s", mw)
out := make(chan beat.Event, 1)
// Start one worker per MetricSet + host combination.
var wg sync.WaitGroup
wg.Add(len(mw.metricSets))
for _, msw := range mw.metricSets {
go func(msw *metricSetWrapper) {
metricsPath := msw.ID()
registry := monitoring.GetNamespace("dataset").GetRegistry()
defer registry.Remove(metricsPath)
defer releaseStats(msw.stats)
defer wg.Done()
defer msw.close()
registry.Add(metricsPath, msw.Metrics(), monitoring.Full)
monitoring.NewString(msw.Metrics(), "starttime").Set(common.Time(time.Now()).String())
msw.run(done, out)
}(msw)
}
// Close the output channel when all writers to the channel have stopped.
go func() {
wg.Wait()
close(out)
debugf("Stopped %s", mw)
}()
return out
}
// String returns a string representation of Wrapper.
func (mw *Wrapper) String() string {
return fmt.Sprintf("Wrapper[name=%s, len(metricSetWrappers)=%d]",
mw.Name(), len(mw.metricSets))
}
// MetricSets return the list of metricsets of the module
func (mw *Wrapper) MetricSets() []*metricSetWrapper {
return mw.metricSets
}
// metricSetWrapper methods
func (msw *metricSetWrapper) run(done <-chan struct{}, out chan<- beat.Event) {
defer logp.Recover(fmt.Sprintf("recovered from panic while fetching "+
"'%s/%s' for host '%s'", msw.module.Name(), msw.Name(), msw.Host()))
// Start each metricset randomly over a period of MaxDelayPeriod.
if msw.module.maxStartDelay > 0 {
delay := time.Duration(rand.Int63n(int64(msw.module.maxStartDelay)))
debugf("%v/%v will start after %v", msw.module.Name(), msw.Name(), delay)
select {
case <-done:
return
case <-time.After(delay):
}
}
debugf("Starting %s", msw)
defer debugf("Stopped %s", msw)
// Events and errors are reported through this.
reporter := &eventReporter{
msw: msw,
out: out,
done: done,
}
switch ms := msw.MetricSet.(type) {
case mb.PushMetricSet:
ms.Run(reporter.V1())
case mb.PushMetricSetV2:
ms.Run(reporter.V2())
case mb.PushMetricSetV2WithContext:
ms.Run(&channelContext{done}, reporter.V2())
case mb.ReportingMetricSet, mb.ReportingMetricSetV2, mb.ReportingMetricSetV2Error, mb.ReportingMetricSetV2WithContext:
msw.startPeriodicFetching(&channelContext{done}, reporter)
default:
// Earlier startup stages prevent this from happening.
logp.Err("MetricSet '%s/%s' does not implement an event producing interface",
msw.Module().Name(), msw.Name())
}
}
// startPeriodicFetching performs an immediate fetch for the MetricSet then it
// begins a continuous timer scheduled loop to fetch data. To stop the loop the
// done channel should be closed.
func (msw *metricSetWrapper) startPeriodicFetching(ctx context.Context, reporter reporter) {
// Indicate that it has been started as periodic fetcher
msw.periodic = true
// Fetch immediately.
msw.fetch(ctx, reporter)
// Start timer for future fetches.
t := time.NewTicker(msw.Module().Config().Period)
defer t.Stop()
for {
select {
case <-reporter.V2().Done():
return
case <-t.C:
msw.fetch(ctx, reporter)
}
}
}
// fetch invokes the appropriate Fetch method for the MetricSet and publishes
// the result using the publisher client. This method will recover from panics
// and log a stack track if one occurs.
func (msw *metricSetWrapper) fetch(ctx context.Context, reporter reporter) {
switch fetcher := msw.MetricSet.(type) {
case mb.ReportingMetricSet:
reporter.StartFetchTimer()
fetcher.Fetch(reporter.V1())
case mb.ReportingMetricSetV2:
reporter.StartFetchTimer()
fetcher.Fetch(reporter.V2())
case mb.ReportingMetricSetV2Error:
reporter.StartFetchTimer()
err := fetcher.Fetch(reporter.V2())
if err != nil {
reporter.V2().Error(err)
logp.Err("Error fetching data for metricset %s.%s: %s", msw.module.Name(), msw.Name(), err)
}
case mb.ReportingMetricSetV2WithContext:
reporter.StartFetchTimer()
err := fetcher.Fetch(ctx, reporter.V2())
if err != nil {
reporter.V2().Error(err)
logp.Err("Error fetching data for metricset %s.%s: %s", msw.module.Name(), msw.Name(), err)
}
default:
panic(fmt.Sprintf("unexpected fetcher type for %v", msw))
}
}
// close closes the underlying MetricSet if it implements the mb.Closer
// interface.
func (msw *metricSetWrapper) close() error {
if closer, ok := msw.MetricSet.(mb.Closer); ok {
return closer.Close()
}
return nil
}
// String returns a string representation of metricSetWrapper.
func (msw *metricSetWrapper) String() string {
return fmt.Sprintf("metricSetWrapper[module=%s, name=%s, host=%s]",
msw.module.Name(), msw.Name(), msw.Host())
}
func (msw *metricSetWrapper) Test(d testing.Driver) {
d.Run(msw.Name(), func(d testing.Driver) {
events := make(chan beat.Event, 1)
done := receiveOneEvent(d, events, msw.module.maxStartDelay+5*time.Second)
msw.run(done, events)
})
}
type reporter interface {
StartFetchTimer()
V1() mb.PushReporter
V2() mb.PushReporterV2
}
// eventReporter implements the Reporter interface which is a callback interface
// used by MetricSet implementations to report an event(s), an error, or an error
// with some additional metadata.
type eventReporter struct {
msw *metricSetWrapper
done <-chan struct{}
out chan<- beat.Event
start time.Time // Start time of the current fetch (or zero for push sources).
}
// startFetchTimer demarcates the start of a new fetch. The elapsed time of a
// fetch is computed based on the time of this call.
func (r *eventReporter) StartFetchTimer() { r.start = time.Now() }
func (r *eventReporter) V1() mb.PushReporter {
return reporterV1{v2: r.V2(), module: r.msw.module.Name()}
}
func (r *eventReporter) V2() mb.PushReporterV2 { return reporterV2{r} }
// channelContext implements context.Context by wrapping a channel
type channelContext struct {
done <-chan struct{}
}
func (r *channelContext) Deadline() (time.Time, bool) { return time.Time{}, false }
func (r *channelContext) Done() <-chan struct{} { return r.done }
func (r *channelContext) Err() error {
select {
case <-r.done:
return context.Canceled
default:
return nil
}
}
func (r *channelContext) Value(key interface{}) interface{} { return nil }
// reporterV1 wraps V2 to provide a v1 interface.
type reporterV1 struct {
v2 mb.PushReporterV2
module string
}
func (r reporterV1) Done() <-chan struct{} { return r.v2.Done() }
func (r reporterV1) Event(event common.MapStr) bool { return r.ErrorWith(nil, event) }
func (r reporterV1) Error(err error) bool { return r.ErrorWith(err, nil) }
func (r reporterV1) ErrorWith(err error, meta common.MapStr) bool {
// Skip nil events without error
if err == nil && meta == nil {
return true
}
return r.v2.Event(mb.TransformMapStrToEvent(r.module, meta, err))
}
type reporterV2 struct {
*eventReporter
}
func (r reporterV2) Done() <-chan struct{} { return r.done }
func (r reporterV2) Error(err error) bool { return r.Event(mb.Event{Error: err}) }
func (r reporterV2) Event(event mb.Event) bool {
if event.Took == 0 && !r.start.IsZero() {
event.Took = time.Since(r.start)
}
if r.msw.periodic {
event.Period = r.msw.Module().Config().Period
}
if event.Timestamp.IsZero() {
if !r.start.IsZero() {
event.Timestamp = r.start
} else {
event.Timestamp = time.Now().UTC()
}
}
if event.Host == "" {
event.Host = r.msw.HostData().SanitizedURI
}
if event.Error == nil {
r.msw.stats.success.Add(1)
} else {
r.msw.stats.failures.Add(1)
}
if event.Namespace == "" {
event.Namespace = r.msw.Registration().Namespace
}
beatEvent := event.BeatEvent(r.msw.module.Name(), r.msw.MetricSet.Name(), r.msw.module.eventModifiers...)
if !writeEvent(r.done, r.out, beatEvent) {
return false
}
r.msw.stats.events.Add(1)
return true
}
// other utility functions
func writeEvent(done <-chan struct{}, out chan<- beat.Event, event beat.Event) bool {
select {
case <-done:
return false
case out <- event:
return true
}
}
func getMetricSetStats(module, name string) *stats {
key := fmt.Sprintf("metricbeat.%s.%s", module, name)
fetchesLock.Lock()
defer fetchesLock.Unlock()
if s := fetches[key]; s != nil {
s.ref++
return s
}
reg := monitoring.Default.NewRegistry(key)
s := &stats{
key: key,
ref: 1,
success: monitoring.NewInt(reg, successesKey),
failures: monitoring.NewInt(reg, failuresKey),
events: monitoring.NewInt(reg, eventsKey),
}
fetches[key] = s
return s
}
func releaseStats(s *stats) {
fetchesLock.Lock()
defer fetchesLock.Unlock()
s.ref--
if s.ref > 0 {
return
}
delete(fetches, s.key)
monitoring.Default.Remove(s.key)
}