-
Notifications
You must be signed in to change notification settings - Fork 183
/
manager.go
454 lines (384 loc) · 13.4 KB
/
manager.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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
package monitors
import (
"fmt"
"sync"
"github.com/davecgh/go-spew/spew"
"github.com/pkg/errors"
"github.com/signalfx/golib/datapoint"
"github.com/signalfx/golib/event"
"github.com/signalfx/golib/trace"
"github.com/signalfx/signalfx-agent/internal/core/config"
"github.com/signalfx/signalfx-agent/internal/core/meta"
"github.com/signalfx/signalfx-agent/internal/core/services"
"github.com/signalfx/signalfx-agent/internal/monitors/collectd"
"github.com/signalfx/signalfx-agent/internal/monitors/types"
"github.com/signalfx/signalfx-agent/internal/utils"
log "github.com/sirupsen/logrus"
)
// MonitorManager coordinates the startup and shutdown of monitors based on the
// configuration provided by the user. Monitors that have discovery rules can
// be injected with multiple services. If a monitor does not have a discovery
// rule (a "static" monitor), it will be started immediately (as soon as
// Configure is called).
type MonitorManager struct {
monitorConfigs map[uint64]config.MonitorCustomConfig
// Keep track of which services go with which monitor
activeMonitors []*ActiveMonitor
badConfigs map[uint64]*config.MonitorConfig
lock sync.Mutex
// Map of service endpoints that have been discovered
discoveredEndpoints map[services.ID]services.Endpoint
DPs chan<- *datapoint.Datapoint
Events chan<- *event.Event
DimensionProps chan<- *types.DimProperties
TraceSpans chan<- *trace.Span
// TODO: AgentMeta is rather hacky so figure out a better way to share agent
// metadata with monitors
agentMeta *meta.AgentMeta
intervalSeconds int
idGenerator func() string
}
// NewMonitorManager creates a new instance of the MonitorManager
func NewMonitorManager(agentMeta *meta.AgentMeta) *MonitorManager {
return &MonitorManager{
monitorConfigs: make(map[uint64]config.MonitorCustomConfig),
activeMonitors: make([]*ActiveMonitor, 0),
badConfigs: make(map[uint64]*config.MonitorConfig),
discoveredEndpoints: make(map[services.ID]services.Endpoint),
idGenerator: utils.NewIDGenerator(),
agentMeta: agentMeta,
}
}
// Configure receives a list of monitor configurations. It will start up any
// static monitors and watch discovered services to see if any match dynamic
// monitors.
func (mm *MonitorManager) Configure(confs []config.MonitorConfig, collectdConf *config.CollectdConfig, intervalSeconds int) {
mm.lock.Lock()
defer mm.lock.Unlock()
mm.intervalSeconds = intervalSeconds
for i := range confs {
confs[i].IntervalSeconds = utils.FirstNonZero(confs[i].IntervalSeconds, intervalSeconds)
}
requireSoloTrue := anyMarkedSolo(confs)
newConfig, deletedHashes := diffNewConfig(confs, mm.allConfigHashes())
if !collectdConf.DisableCollectd {
// By configuring collectd with the monitor manager, we absolve the monitor
// instances of having to know about collectd config, which makes it easier
// to create monitor config from disparate sources such as from observers.
if err := collectd.ConfigureMainCollectd(collectdConf); err != nil {
log.WithFields(log.Fields{
"error": err,
"collectdConfig": spew.Sdump(collectdConf),
}).Error("Could not configure collectd")
}
}
for _, hash := range deletedHashes {
mm.deleteMonitorsByConfigHash(hash)
delete(mm.monitorConfigs, hash)
delete(mm.badConfigs, hash)
}
for i := range newConfig {
conf := newConfig[i]
hash := conf.Hash()
if requireSoloTrue && !conf.Solo {
log.Infof("Solo mode is active, skipping monitor of type %s", conf.Type)
continue
}
monConfig, err := mm.handleNewConfig(&conf)
if err != nil {
log.WithFields(log.Fields{
"monitorType": conf.Type,
"error": err,
}).Error("Could not process configuration for monitor")
conf.ValidationError = err.Error()
mm.badConfigs[hash] = &conf
continue
}
mm.monitorConfigs[hash] = monConfig
}
}
func (mm *MonitorManager) allConfigHashes() map[uint64]bool {
hashes := make(map[uint64]bool)
for h := range mm.monitorConfigs {
hashes[h] = true
}
for h := range mm.badConfigs {
hashes[h] = true
}
return hashes
}
// Returns the any new configs and any removed config hashes
func diffNewConfig(confs []config.MonitorConfig, oldHashes map[uint64]bool) ([]config.MonitorConfig, []uint64) {
newConfigHashes := make(map[uint64]bool)
var newConfig []config.MonitorConfig
for i := range confs {
hash := confs[i].Hash()
if !oldHashes[hash] {
newConfig = append(newConfig, confs[i])
}
if newConfigHashes[hash] {
log.WithFields(log.Fields{
"monitorType": confs[i].Type,
"config": confs[i],
}).Error("Monitor config is duplicated")
continue
}
newConfigHashes[hash] = true
}
var deletedHashes []uint64
for hash := range oldHashes {
// If we didn't see it in the latest config slice then we need to
// delete anything using it.
if !newConfigHashes[hash] {
deletedHashes = append(deletedHashes, hash)
}
}
return newConfig, deletedHashes
}
func (mm *MonitorManager) handleNewConfig(conf *config.MonitorConfig) (config.MonitorCustomConfig, error) {
monConfig, err := getCustomConfigForMonitor(conf)
if err != nil {
return nil, err
}
if configOnlyAllowsSingleInstance(monConfig) {
if len(mm.monitorConfigsForType(conf.Type)) > 0 {
return nil, fmt.Errorf("Monitor type %s only allows a single instance at a time", conf.Type)
}
}
// No discovery rule means that the monitor should run from the start
if conf.DiscoveryRule == "" {
return monConfig, mm.createAndConfigureNewMonitor(monConfig, nil)
}
mm.makeMonitorsForMatchingEndpoints(monConfig)
// We need to go and see if any discovered endpoints should be
// monitored by this config, if they aren't already.
return monConfig, nil
}
func (mm *MonitorManager) makeMonitorsForMatchingEndpoints(conf config.MonitorCustomConfig) {
for id, endpoint := range mm.discoveredEndpoints {
// Self configured endpoints are monitored immediately upon being
// created and never need to be matched against discovery rules.
if endpoint.Core().IsSelfConfigured() {
continue
}
log.WithFields(log.Fields{
"monitorType": conf.MonitorConfigCore().Type,
"discoveryRule": conf.MonitorConfigCore().DiscoveryRule,
"endpoint": endpoint,
}).Debug("Trying to find config that matches discovered endpoint")
if mm.isEndpointIDMonitoredByConfig(conf, id) {
continue
}
if matched, err := mm.monitorEndpointIfRuleMatches(conf, endpoint); matched {
if err != nil {
log.WithFields(log.Fields{
"error": err,
"endpointID": endpoint.Core().ID,
"monitorType": conf.MonitorConfigCore().Type,
}).Error("Error monitoring endpoint that matched rule")
} else {
log.WithFields(log.Fields{
"endpointID": endpoint.Core().ID,
"monitorType": conf.MonitorConfigCore().Type,
}).Info("Now monitoring discovered endpoint")
}
}
}
}
func (mm *MonitorManager) isEndpointIDMonitoredByConfig(conf config.MonitorCustomConfig, id services.ID) bool {
for _, am := range mm.activeMonitors {
if conf.MonitorConfigCore().Hash() == am.configHash {
return true
}
}
return false
}
// Returns true is the service did match a rule in this monitor config
func (mm *MonitorManager) monitorEndpointIfRuleMatches(config config.MonitorCustomConfig, endpoint services.Endpoint) (bool, error) {
if config.MonitorConfigCore().DiscoveryRule == "" || !services.DoesServiceMatchRule(endpoint, config.MonitorConfigCore().DiscoveryRule) {
return false, nil
}
err := mm.createAndConfigureNewMonitor(config, endpoint)
if err != nil {
return false, err
}
return true, nil
}
// EndpointAdded should be called when a new service is discovered
func (mm *MonitorManager) EndpointAdded(endpoint services.Endpoint) {
mm.lock.Lock()
defer mm.lock.Unlock()
ensureProxyingDisabledForService(endpoint)
mm.discoveredEndpoints[endpoint.Core().ID] = endpoint
// If the endpoint has a monitor type specified, then it is expected to
// have all of its configuration already set in the endpoint and discovery
// rules will be ignored.
if endpoint.Core().IsSelfConfigured() {
mm.monitorSelfConfiguredEndpoint(endpoint)
return
}
mm.findConfigForMonitorAndRun(endpoint)
}
func (mm *MonitorManager) monitorSelfConfiguredEndpoint(endpoint services.Endpoint) {
monitorType := endpoint.Core().MonitorType
conf := &config.MonitorConfig{
Type: monitorType,
// This will get overridden by the endpoint configuration if interval
// was specified
IntervalSeconds: mm.intervalSeconds,
}
monConfig, err := getCustomConfigForMonitor(conf)
if err != nil {
log.WithFields(log.Fields{
"error": err,
"monitorType": monitorType,
}).Error("Could not create monitor config for self-configured endpoint")
return
}
err = mm.createAndConfigureNewMonitor(monConfig, endpoint)
if err != nil {
log.WithFields(log.Fields{
"error": err,
"endpoint": endpoint,
}).Error("Could not create monitor for self-configured endpoint")
return
}
}
func (mm *MonitorManager) findConfigForMonitorAndRun(endpoint services.Endpoint) {
monitoring := false
for _, config := range mm.monitorConfigs {
matched, err := mm.monitorEndpointIfRuleMatches(config, endpoint)
monitoring = matched || monitoring
if err != nil {
log.WithFields(log.Fields{
"error": err,
"config": config,
"endpoint": endpoint,
}).Error("Could not monitor new endpoint")
}
}
if !monitoring {
log.WithFields(log.Fields{
"endpoint": endpoint,
}).Debug("Endpoint added that doesn't match any discovery rules")
}
}
// endpoint may be nil for static monitors
func (mm *MonitorManager) createAndConfigureNewMonitor(config config.MonitorCustomConfig, endpoint services.Endpoint) error {
id := types.MonitorID(mm.idGenerator())
log.WithFields(log.Fields{
"monitorType": config.MonitorConfigCore().Type,
"discoveryRule": config.MonitorConfigCore().DiscoveryRule,
"monitorID": id,
}).Info("Creating new monitor")
instance := newMonitor(config.MonitorConfigCore().Type, id)
if instance == nil {
return errors.Errorf("Could not create new monitor of type %s", config.MonitorConfigCore().Type)
}
configHash := config.MonitorConfigCore().Hash()
output := &monitorOutput{
monitorType: config.MonitorConfigCore().Type,
monitorID: id,
notHostSpecific: config.MonitorConfigCore().DisableHostDimensions,
disableEndpointDimensions: config.MonitorConfigCore().DisableEndpointDimensions,
filter: config.MonitorConfigCore().Filter,
configHash: configHash,
endpoint: endpoint,
dpChan: mm.DPs,
eventChan: mm.Events,
dimPropChan: mm.DimensionProps,
spanChan: mm.TraceSpans,
extraDims: map[string]string{},
}
am := &ActiveMonitor{
id: id,
configHash: configHash,
instance: instance,
endpoint: endpoint,
agentMeta: mm.agentMeta,
output: output,
}
if err := am.configureMonitor(config); err != nil {
return err
}
mm.activeMonitors = append(mm.activeMonitors, am)
return nil
}
func (mm *MonitorManager) monitorsForEndpointID(id services.ID) (out []*ActiveMonitor) {
for i := range mm.activeMonitors {
if mm.activeMonitors[i].endpointID() == id {
out = append(out, mm.activeMonitors[i])
}
}
return // Named return value
}
func (mm *MonitorManager) monitorConfigsForType(monitorType string) []*config.MonitorCustomConfig {
var out []*config.MonitorCustomConfig
for _, conf := range mm.monitorConfigs {
if conf.MonitorConfigCore().Type == monitorType {
out = append(out, &conf)
}
}
return out
}
func (mm *MonitorManager) isServiceMonitored(id services.ID) bool {
return len(mm.monitorsForEndpointID(id)) > 0
}
// EndpointRemoved should be called by observers when a service endpoint was
// removed.
func (mm *MonitorManager) EndpointRemoved(endpoint services.Endpoint) {
mm.lock.Lock()
defer mm.lock.Unlock()
delete(mm.discoveredEndpoints, endpoint.Core().ID)
monitors := mm.monitorsForEndpointID(endpoint.Core().ID)
for _, am := range monitors {
am.doomed = true
}
mm.deleteDoomedMonitors()
log.WithFields(log.Fields{
"endpoint": endpoint,
}).Info("No longer considering endpoint")
}
func (mm *MonitorManager) isEndpointMonitored(endpoint services.Endpoint) bool {
monitors := mm.monitorsForEndpointID(endpoint.Core().ID)
return len(monitors) > 0
}
func (mm *MonitorManager) deleteMonitorsByConfigHash(hash uint64) {
for i := range mm.activeMonitors {
if mm.activeMonitors[i].configHash == hash {
log.WithFields(log.Fields{
"config": mm.activeMonitors[i].config,
}).Info("Shutting down monitor due to config hash change")
mm.activeMonitors[i].doomed = true
}
}
mm.deleteDoomedMonitors()
}
func (mm *MonitorManager) deleteDoomedMonitors() {
newActiveMonitors := []*ActiveMonitor{}
for i := range mm.activeMonitors {
am := mm.activeMonitors[i]
if am.doomed {
log.WithFields(log.Fields{
"monitorID": am.id,
"monitorType": am.config.MonitorConfigCore().Type,
"discoveryRule": am.config.MonitorConfigCore().DiscoveryRule,
}).Info("Shutting down monitor")
am.Shutdown()
} else {
newActiveMonitors = append(newActiveMonitors, am)
}
}
mm.activeMonitors = newActiveMonitors
}
// Shutdown will shutdown all managed monitors and deinitialize the manager.
func (mm *MonitorManager) Shutdown() {
mm.lock.Lock()
defer mm.lock.Unlock()
for i := range mm.activeMonitors {
mm.activeMonitors[i].doomed = true
}
mm.deleteDoomedMonitors()
mm.activeMonitors = nil
mm.discoveredEndpoints = nil
}