forked from aws/amazon-cloudwatch-agent-test
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontainer_insights_util.go
More file actions
360 lines (316 loc) · 10.5 KB
/
Copy pathcontainer_insights_util.go
File metadata and controls
360 lines (316 loc) · 10.5 KB
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT
//go:build !windows
package metric
import (
"encoding/json"
"errors"
"fmt"
"log"
"math"
"math/rand"
"sort"
"strconv"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/cloudwatch/types"
"github.com/aws/amazon-cloudwatch-agent-test/environment"
"github.com/aws/amazon-cloudwatch-agent-test/test/metric_value_benchmark/eks_resources"
"github.com/aws/amazon-cloudwatch-agent-test/test/status"
"github.com/aws/amazon-cloudwatch-agent-test/util/awsservice"
)
const (
dimDelimiter = "-"
ContainerInsightsNamespace = "ContainerInsights"
)
type dimToMetrics struct {
// dim keys as string with dimDelimiter(-) eg. ClusterName-Namespace
dimStr string
// metric names to their dimensions with values. Dimension sets will be used for metric data validations
metrics map[string][][]types.Dimension
}
func ValidateMetrics(env *environment.MetaData, metricFilter string, expectedDimsToMetrics map[string][]string) []status.TestResult {
var results []status.TestResult
dimsToMetrics := getMetricsInClusterDimension(env, metricFilter)
for dims, metrics := range expectedDimsToMetrics {
var actual map[string][][]types.Dimension
// find matching dim set from fetched and processed metric-dims groups
for _, dtm := range dimsToMetrics {
if dtm.dimStr == dims {
actual = dtm.metrics
break
}
}
// expected dim set doesn't exist
if len(actual) < 1 {
results = append(results, status.TestResult{
Name: dims,
Status: status.FAILED,
})
log.Printf("ValidateMetrics failed with missing dimension set: %s", dims)
// keep testing other dims or fail early?
continue
}
results = append(results, validateMetricsAvailability(dims, metrics, actual))
for _, m := range metrics {
// this is to prevent panic with rand.Intn when metrics are not yet ready in a cluster
if _, ok := actual[m]; !ok {
results = append(results, status.TestResult{
Name: dims,
Status: status.FAILED,
})
log.Printf("ValidateMetrics failed with missing metric: %s", m)
continue
}
// pick a random dimension set to test metric data OR test all dimension sets which might be overkill
randIdx := rand.Intn(len(actual[m]))
results = append(results, validateMetricValue(m, actual[m][randIdx]))
}
}
return results
}
func getMetricsInClusterDimension(env *environment.MetaData, metricFilter string) []dimToMetrics { //map[string]map[string]interface{} {
listFetcher := Fetcher{}
log.Printf("Fetching by cluster dimension")
dims := []types.Dimension{
{
Name: aws.String("ClusterName"),
Value: aws.String(env.EKSClusterName),
},
}
metrics, err := listFetcher.Fetch(ContainerInsightsNamespace, "", dims)
if err != nil {
log.Println("failed to fetch metric list", err)
return nil
}
if len(metrics) < 1 {
log.Println("cloudwatch metric list is empty")
return nil
}
var results []dimToMetrics
for _, m := range metrics {
// filter by metric name filter
if metricFilter != "" && !strings.Contains(*m.MetricName, metricFilter) {
continue
}
var dims []string
for _, d := range m.Dimensions {
dims = append(dims, *d.Name)
}
sort.Sort(sort.StringSlice(dims))
dimsKey := strings.Join(dims, dimDelimiter)
log.Printf("processing dims: %s", dimsKey)
var dtm dimToMetrics
for _, ele := range results {
if ele.dimStr == dimsKey {
dtm = ele
break
}
}
if dtm.dimStr == "" {
dtm = dimToMetrics{
dimStr: dimsKey,
metrics: make(map[string][][]types.Dimension),
}
results = append(results, dtm)
}
dtm.metrics[*m.MetricName] = append(dtm.metrics[*m.MetricName], m.Dimensions)
}
return results
}
func validateMetricsAvailability(dims string, expected []string, actual map[string][][]types.Dimension) status.TestResult {
testResult := status.TestResult{
Name: dims,
Status: status.FAILED,
}
if compareMetrics(expected, actual) {
testResult.Status = status.SUCCESSFUL
} else {
log.Printf("validateMetricsAvailability failed for %s", dims)
}
return testResult
}
func compareMetrics(expected []string, actual map[string][][]types.Dimension) bool {
if len(expected) != len(actual) {
log.Printf("the count of fetched metrics do not match with expected count: expected-%v, actual-%v\n", len(expected), len(actual))
expectedSet := make(map[string]struct{})
for _, key := range expected {
expectedSet[key] = struct{}{}
}
for key := range actual {
if _, exists := expectedSet[key]; !exists {
log.Printf("Unexpected metric in actual output : %s\n", key)
}
}
// Find missing metrics in expected output
for _, key := range expected {
if _, exists := actual[key]; !exists {
log.Printf("Missing metric in actual output: %s\n", key)
}
}
return false
}
for _, key := range expected {
if _, ok := actual[key]; !ok {
log.Printf("Missing metric in actual: %s\n", key)
return false
}
}
return true
}
func validateMetricValue(name string, dims []types.Dimension) status.TestResult {
log.Printf("validateMetricValue with metric: %s", name)
testResult := status.TestResult{
Name: name,
Status: status.FAILED,
}
valueFetcher := MetricValueFetcher{}
values, err := valueFetcher.Fetch(ContainerInsightsNamespace, name, dims, SAMPLE_COUNT, MinuteStatPeriod)
if err != nil {
log.Println("failed to fetch metrics", err)
return testResult
}
if !IsAllValuesGreaterThanOrEqualToExpectedValue(name, values, 0) {
return testResult
}
testResult.Status = status.SUCCESSFUL
return testResult
}
func ValidateLogs(env *environment.MetaData) status.TestResult {
testResult := status.TestResult{
Name: "emf-logs",
Status: status.FAILED,
}
end := time.Now()
start := end.Add(time.Duration(-3) * time.Minute)
group := fmt.Sprintf("/aws/containerinsights/%s/performance", env.EKSClusterName)
// need to get the instances used for the EKS cluster
eKSInstances, err := awsservice.GetEKSInstances(env.EKSClusterName)
if err != nil {
log.Println("failed to get EKS instances", err)
return testResult
}
for _, instance := range eKSInstances {
stream := *instance.InstanceName
err = awsservice.ValidateLogs(
group,
stream,
&start,
&end,
awsservice.AssertLogsNotEmpty(),
//awsservice.AssertNoDuplicateLogs(),
awsservice.AssertPerLog(
awsservice.AssertLogSchema(func(message string) (string, error) {
var eksClusterType awsservice.EKSClusterType
innerErr := json.Unmarshal([]byte(message), &eksClusterType)
if innerErr != nil {
return "", fmt.Errorf("failed to unmarshal log file: %w", innerErr)
}
//log.Printf("eksClusterType is: %s", eksClusterType.Type)
jsonSchema, ok := eks_resources.EksClusterValidationMap[eksClusterType.Type]
if !ok {
return "", errors.New("invalid cluster type provided")
}
return jsonSchema, nil
}),
awsservice.AssertLogContainsSubstring(fmt.Sprintf("\"ClusterName\":\"%s\"", env.EKSClusterName)),
),
)
if err != nil {
log.Printf("log validation (%s/%s) failed: %v", group, stream, err)
return testResult
}
}
testResult.Status = status.SUCCESSFUL
return testResult
}
func ValidateLogsFrequency(env *environment.MetaData) status.TestResult {
testResult := status.TestResult{
Name: "emf-logs-frequency",
Status: status.FAILED,
}
end := time.Now().Add(time.Duration(-2) * time.Minute).Truncate(time.Minute)
start := end.Add(time.Duration(-1) * time.Minute)
group := fmt.Sprintf("/aws/containerinsights/%s/performance", env.EKSClusterName)
// need to get the instances used for the EKS cluster
eKSInstances, err := awsservice.GetEKSInstances(env.EKSClusterName)
if err != nil {
log.Println("failed to get EKS instances", err)
return testResult
}
for _, instance := range eKSInstances {
stream := *instance.InstanceName
frequencyMap, err := awsservice.GetLogEventCountPerType(group, stream, &start, &end)
for logType, expectedFrequency := range eks_resources.EksClusterFrequencyValidationMap {
log.Printf("logs with no logtype : %d", frequencyMap[awsservice.NoLogTypeFound])
actualFrequency, ok := frequencyMap[logType]
if !ok {
log.Printf("no log with the expected logtype found : %s, start time : %s", logType, start.GoString())
return testResult
}
if actualFrequency != expectedFrequency {
log.Printf("log frequency validation failed for type: %s, expected: %d, actual: %d, start time: %s", logType, expectedFrequency, actualFrequency, start.GoString())
return testResult
}
}
if err != nil {
log.Printf("log validation (%s/%s) failed: %v, start time : %s", group, stream, err, start)
return testResult
}
}
testResult.Status = status.SUCCESSFUL
return testResult
}
func ValidateNeuronCoreUtilizationValuesLogs(env *environment.MetaData) status.TestResult {
const core = "core"
testResult := status.TestResult{
Name: "emf-logs-neuron-core-utilization",
Status: status.FAILED,
}
var testFailed = false
end := time.Now().Add(-2 * time.Minute).Truncate(time.Minute)
start := end.Add(-1 * time.Minute)
group := fmt.Sprintf("/aws/containerinsights/%s/performance", env.EKSClusterName)
// need to get the instances used for the EKS cluster
eKSInstances, err := awsservice.GetEKSInstances(env.EKSClusterName)
if err != nil {
log.Println("failed to get EKS instances", err)
return testResult
}
for _, instance := range eKSInstances {
stream := *instance.InstanceName
coreMap, err := awsservice.GetNeuronCoreUtilizationPerCore(group, stream, &start, &end)
if err != nil {
log.Printf("log validation (%s/%s) failed: %v, start time : %s, error is : %s", group, stream, err, start, err)
return testResult
}
// We expect 32 Cores from the current test, anything less or more is a bug
if len(coreMap) != 32 {
log.Printf("32 Cores not found")
var coreMapStr strings.Builder
for k, v := range coreMap {
coreMapStr.WriteString(fmt.Sprintf("%s: %f, ", k, v))
}
log.Printf("coreMap: %s", coreMapStr.String())
testFailed = true
}
// Check if coreMap has the expected core utilization values
for coreKey, actualValue := range coreMap {
if strings.HasPrefix(coreKey, core) {
coreNumStr := strings.TrimPrefix(coreKey, core)
expectedValue, err := strconv.Atoi(coreNumStr)
if err != nil || math.Round(actualValue) != float64(expectedValue) {
log.Printf("Core utilization validation failed: expected %s:%d, got %v",
coreKey, expectedValue, actualValue)
testFailed = true
}
}
}
}
testResult.Status = status.SUCCESSFUL
if testFailed {
testResult.Status = status.FAILED
}
return testResult
}