-
Notifications
You must be signed in to change notification settings - Fork 7
/
model.go
379 lines (338 loc) · 12.1 KB
/
model.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
package elastic
import (
"strings"
"sync"
"time"
"github.com/gwos/tcg/config"
"github.com/gwos/tcg/connectors"
ecClients "github.com/gwos/tcg/connectors/elastic/clients"
"github.com/gwos/tcg/sdk/clients"
"github.com/gwos/tcg/sdk/transit"
"github.com/rs/zerolog/log"
)
var doOnce sync.Once
// status message templates for different statuses
// if template for service's status not listed service's status text will be only thresholds if they exist,
// otherwise empty
var initStatusMessages = map[transit.MonitorStatus]string{
transit.ServiceOk: "Query matched {value} messages in the last {interval}.",
transit.ServiceWarning: "Query matched {value} messages in the last {interval}.",
transit.ServiceUnscheduledCritical: "Query matched {value} messages in the last {interval}.",
transit.ServiceScheduledCritical: "Query matched {value} messages in the last {interval}.",
transit.ServicePending: "Service Pending.",
transit.ServiceUnknown: "Service Unknown.",
}
// MonitoringState describes state
type MonitoringState struct {
Metrics map[string]transit.MetricDefinition
Hosts map[string]monitoringHost
HostGroups map[string]map[string]struct{}
}
type monitoringService struct {
name string
hits int
timeInterval *transit.TimeInterval
}
type monitoringHost struct {
name string
services map[string]monitoringService
hostGroups []string
}
func (cfg *ExtConfig) initMonitoringState(previousState MonitoringState, esClient *ecClients.EsClient) MonitoringState {
currentState := MonitoringState{
Metrics: make(map[string]transit.MetricDefinition),
Hosts: make(map[string]monitoringHost),
}
for _, metrics := range cfg.Views {
for metricName, metric := range metrics {
if metric.Monitored {
currentState.Metrics[metricName] = metric
}
}
}
doOnce.Do(func() {
log.Info().Msgf("initializing state with GW hosts for agent %s", cfg.AgentID)
// add hosts form GW to current state
if cfg.GWConnections == nil || len(cfg.GWConnections) == 0 {
log.Error().Msg("could not get GW hosts to initialize state: GW connections are not set")
} else {
gwHosts := initGwHosts(cfg.AppType, cfg.AgentID, cfg.GWConnections)
if gwHosts != nil {
currentState.Hosts = gwHosts
} else {
log.Info().Msg("no GW hosts received")
}
}
})
// update with hosts from prev runs
for _, host := range previousState.Hosts {
currentState.Hosts[host.name] = host
}
// update with hosts extracted from ES right now
esHosts := cfg.initEsHosts(esClient)
for _, host := range esHosts {
currentState.Hosts[host.name] = host
}
// nullify services
if currentState.Metrics != nil {
for _, host := range currentState.Hosts {
host.services = make(map[string]monitoringService, len(currentState.Metrics))
for metricName := range currentState.Metrics {
service := monitoringService{name: metricName, hits: 0}
host.services[metricName] = service
}
currentState.Hosts[host.name] = host
}
}
return currentState
}
func (monitoringState *MonitoringState) updateHosts(values map[string]int, serviceName string,
timeInterval *transit.TimeInterval) {
for hostName, value := range values {
if host, ok := monitoringState.Hosts[hostName]; ok {
if service, ok := host.services[serviceName]; ok {
service.hits = value
if service.timeInterval == nil {
service.timeInterval = timeInterval
}
host.services[serviceName] = service
monitoringState.Hosts[hostName] = host
}
}
}
}
func (monitoringState *MonitoringState) toTransitResources() ([]transit.MonitoredResource, []transit.InventoryResource) {
hosts := monitoringState.Hosts
mrs := make([]transit.MonitoredResource, 0, len(hosts))
irs := make([]transit.InventoryResource, 0, len(hosts))
for _, host := range hosts {
monitoredServices, inventoryServices := host.toTransitResources(monitoringState.Metrics)
inventoryResource := connectors.CreateInventoryResource(host.name, inventoryServices)
irs = append(irs, inventoryResource)
monitoredResource, err := connectors.CreateResource(host.name, monitoredServices)
if err != nil {
log.Err(err).Msgf("could not create resource %s", host.name)
}
if monitoredResource != nil {
mrs = append(mrs, *monitoredResource)
}
}
return mrs, irs
}
func (host monitoringHost) toTransitResources(metricDefinitions map[string]transit.MetricDefinition) ([]transit.MonitoredService, []transit.InventoryService) {
monitoredServices := make([]transit.MonitoredService, 0, len(host.services))
inventoryServices := make([]transit.InventoryService, 0, len(host.services))
if metricDefinitions == nil {
return monitoredServices, inventoryServices
}
for serviceName, service := range host.services {
if metricDefinition, has := metricDefinitions[serviceName]; has {
customServiceName := connectors.Name(serviceName, metricDefinition.CustomName)
inventoryService := connectors.CreateInventoryService(customServiceName, host.name)
inventoryServices = append(inventoryServices, inventoryService)
metricBuilder := connectors.MetricBuilder{
Name: serviceName,
CustomName: metricDefinition.CustomName,
ComputeType: metricDefinition.ComputeType,
Expression: metricDefinition.Expression,
Value: service.hits,
UnitType: transit.UnitCounter,
Warning: metricDefinition.WarningThreshold,
Critical: metricDefinition.CriticalThreshold,
Graphed: metricDefinition.Graphed,
}
var intervalReplacement string
if service.timeInterval != nil {
metricBuilder.StartTimestamp = service.timeInterval.StartTime
metricBuilder.EndTimestamp = service.timeInterval.EndTime
endTimeNano := service.timeInterval.EndTime.UnixNano()
startTimeNano := service.timeInterval.StartTime.UnixNano()
timeInterval := time.Duration(endTimeNano - startTimeNano)
intervalReplacement = connectors.FormatTimeForStatusMessage(timeInterval, time.Minute)
}
// copy status message templates already replacing {interval} where applicable
statusMessages := make(map[transit.MonitorStatus]string)
for status, statusMessage := range initStatusMessages {
var message string
// if service has its own interval replace "{interval}" pattern in all status messages with this value now
// otherwise it will be replaced by check interval in minutes
if strings.Contains(statusMessage, "{interval}") && intervalReplacement != "" {
message = strings.ReplaceAll(statusMessage, "{interval}", intervalReplacement)
} else {
message = statusMessage
}
statusMessages[status] = message
}
monitoredService, err := connectors.BuildServiceForMetricWithStatusText(host.name, metricBuilder, statusMessages)
if err != nil {
log.Err(err).Msgf("could not create service %s:%s", host.name, customServiceName)
}
if monitoredService != nil {
monitoredServices = append(monitoredServices, *monitoredService)
}
}
}
return monitoredServices, inventoryServices
}
func (monitoringState *MonitoringState) toResourceGroups() []transit.ResourceGroup {
groups := monitoringState.buildGroups()
rgs := make([]transit.ResourceGroup, 0, len(groups))
for group, hostsInGroup := range groups {
monitoredResourceRefs := make([]transit.ResourceRef, 0, len(hostsInGroup))
for host := range hostsInGroup {
monitoredResourceRef := connectors.CreateResourceRef(host, "", transit.ResourceTypeHost)
monitoredResourceRefs = append(monitoredResourceRefs, monitoredResourceRef)
}
resourceGroup := connectors.CreateResourceGroup(group, group, transit.HostGroup, monitoredResourceRefs)
rgs = append(rgs, resourceGroup)
}
return rgs
}
func (monitoringState *MonitoringState) buildGroups() map[string]map[string]struct{} {
groups := make(map[string]map[string]struct{})
for hostName, host := range monitoringState.Hosts {
for _, groupName := range host.hostGroups {
if groupName == "" {
continue
}
if group, exists := groups[groupName]; exists {
group[hostName] = struct{}{}
} else {
group := make(map[string]struct{})
group[hostName] = struct{}{}
groups[groupName] = group
}
groups[groupName][hostName] = struct{}{}
}
}
monitoringState.HostGroups = groups
return groups
}
func initGwHosts(appType string, agentID string, gwConnections config.GWConnections) map[string]monitoringHost {
gwHosts := make(map[string]monitoringHost)
for _, gwConnection := range gwConnections {
gwClient := clients.GWClient{
AppName: appType,
AppType: appType,
GWConnection: (*clients.GWConnection)(gwConnection),
}
err := gwClient.Connect()
if err != nil {
log.Err(err).Msg("could not connect to GW to get hosts to initialize state")
continue
}
gwServices, err := gwClient.GetServicesByAgent(agentID)
if err != nil || gwServices == nil {
log.Error().Err(err).
Msg("could not get GW hosts to initialize state")
continue
}
var hostNames []string
for _, gwService := range gwServices.Services {
if _, exists := gwHosts[gwService.HostName]; !exists {
host := monitoringHost{
name: gwService.HostName,
}
gwHosts[gwService.HostName] = host
hostNames = append(hostNames, gwService.HostName)
}
}
if len(hostNames) > 0 {
gwHostGroups, err := gwClient.GetHostGroupsByHostNamesAndAppType(hostNames, appType)
if err != nil || gwHostGroups == nil {
log.Error().Err(err).
Msg("could not get GW host groups to initialize state")
continue
}
for _, gwHostGroup := range gwHostGroups.HostGroups {
for _, gwHost := range gwHostGroup.Hosts {
if host, exists := gwHosts[gwHost.HostName]; exists {
hostGroups := host.hostGroups
hostGroups = append(hostGroups, gwHostGroup.Name)
host.hostGroups = hostGroups
gwHosts[gwHost.HostName] = host
}
}
}
}
}
return gwHosts
}
func (cfg *ExtConfig) initEsHosts(esClient *ecClients.EsClient) map[string]monitoringHost {
esHosts := make(map[string]monitoringHost)
hostNameField := cfg.HostNameField
hostGroupField := &cfg.HostGroupField
groupNameByUser := cfg.GroupNameByUser
if groupNameByUser {
hostGroupField = nil
}
fieldNames := []string{hostNameField}
if hostGroupField != nil {
fieldNames = append(fieldNames, *hostGroupField)
}
isAggregatable, err := esClient.IsAggregatable(fieldNames, nil)
if err != nil {
log.Error().Msg("could not retrieve ES hosts")
return esHosts
}
allAggregatable := true
if !isAggregatable[hostNameField] && !strings.HasSuffix(hostNameField, ".keyword") {
allAggregatable = false
hostNameField = hostNameField + ".keyword"
}
if hostGroupField != nil {
if !isAggregatable[*hostGroupField] && !strings.HasSuffix(*hostGroupField, ".keyword") {
allAggregatable = false
newHostGroupField := *hostGroupField + ".keyword"
hostGroupField = &newHostGroupField
}
}
if !allAggregatable {
fieldNames = []string{hostNameField}
if hostGroupField != nil {
fieldNames = append(fieldNames, *hostGroupField)
}
isAggregatable, _ = esClient.IsAggregatable(fieldNames, nil)
if isAggregatable[hostNameField] && (hostGroupField == nil || isAggregatable[*hostGroupField]) {
allAggregatable = true
}
}
if !allAggregatable {
log.Error().
Strs("fieldNames", fieldNames).
Msgf("could not retrieve ES hosts: not all fields are aggregatable")
return esHosts
}
cfg.HostNameField = hostNameField
if !groupNameByUser && hostGroupField != nil {
cfg.HostGroupField = *hostGroupField
}
keys, _ := esClient.GetHosts(cfg.HostNameField, hostGroupField)
for _, key := range keys {
hostNameKey := key.Host
hostGroupKey := key.HostGroup
if esHost, exists := esHosts[hostNameKey]; exists {
if !groupNameByUser && hostGroupKey != nil {
esHostGroups := esHost.hostGroups
esHostGroups = append(esHostGroups, *hostGroupKey)
esHost.hostGroups = esHostGroups
esHosts[hostNameKey] = esHost
}
} else {
var hostGroups []string
if groupNameByUser {
hostGroups = []string{cfg.HostGroupField}
} else {
if hostGroupKey != nil {
hostGroups = []string{*hostGroupKey}
}
}
host := monitoringHost{
name: hostNameKey,
hostGroups: hostGroups,
}
esHosts[hostNameKey] = host
}
}
return esHosts
}