forked from aws/amazon-cloudwatch-agent-test
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcloudwatchlogs.go
More file actions
424 lines (360 loc) · 12.7 KB
/
Copy pathcloudwatchlogs.go
File metadata and controls
424 lines (360 loc) · 12.7 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
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT
package awsservice
import (
"context"
"encoding/json"
"errors"
"fmt"
"log"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs"
"github.com/aws/aws-sdk-go-v2/service/cloudwatchlogs/types"
"github.com/qri-io/jsonschema"
)
const (
logStreamRetry = 20
retryInterval = 10 * time.Second
NoLogTypeFound = "NoLogTypeFound"
)
// catch ResourceNotFoundException when deleting the log group and log stream, as these
// are not useful exceptions to log errors on during cleanup
var rnf *types.ResourceNotFoundException
// DeleteLogGroupAndStream cleans up a log group and stream by name. This gracefully handles
// ResourceNotFoundException errors from calling the APIs
func DeleteLogGroupAndStream(logGroupName, logStreamName string) {
DeleteLogStream(logGroupName, logStreamName)
DeleteLogGroup(logGroupName)
}
// DeleteLogStream cleans up log stream by name
func DeleteLogStream(logGroupName, logStreamName string) {
_, err := CwlClient.DeleteLogStream(ctx, &cloudwatchlogs.DeleteLogStreamInput{
LogGroupName: aws.String(logGroupName),
LogStreamName: aws.String(logStreamName),
})
if err != nil && !errors.As(err, &rnf) {
log.Printf("Error occurred while deleting log stream %s: %v", logStreamName, err)
}
}
// DeleteLogGroup cleans up log group by name
func DeleteLogGroup(logGroupName string) {
_, err := CwlClient.DeleteLogGroup(ctx, &cloudwatchlogs.DeleteLogGroupInput{
LogGroupName: aws.String(logGroupName),
})
if err != nil && !errors.As(err, &rnf) {
log.Printf("Error occurred while deleting log group %s: %v", logGroupName, err)
}
}
// ValidateLogs queries a given LogGroup/LogStream combination given the start and end times, and executes an
// arbitrary validator function on the found logs.
func ValidateLogs(logGroup, logStream string, since, until *time.Time, validators ...LogEventsValidator) error {
log.Printf("Checking %s/%s", logGroup, logStream)
events, err := GetLogsSince(logGroup, logStream, since, until)
if err != nil {
return err
}
for _, validator := range validators {
if err = validator(events); err != nil {
return err
}
}
return nil
}
// GetLogsSince makes GetLogEvents API calls, paginates through the results for the given time frame, and returns
// the raw log strings
func GetLogsSince(logGroup, logStream string, since, until *time.Time) ([]types.OutputLogEvent, error) {
var events []types.OutputLogEvent
// https://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_GetLogEvents.html
// GetLogEvents can return an empty result while still having more log events on a subsequent page,
// so rather than expecting all the events to show up in one GetLogEvents API call, we need to paginate.
params := &cloudwatchlogs.GetLogEventsInput{
LogGroupName: aws.String(logGroup),
LogStreamName: aws.String(logStream),
StartFromHead: aws.Bool(true), // read from the beginning
}
if since != nil {
params.StartTime = aws.Int64(since.UnixMilli())
}
if until != nil {
params.EndTime = aws.Int64(until.UnixMilli())
}
var nextToken *string
attempts := 0
for {
if nextToken != nil {
params.NextToken = nextToken
}
output, err := CwlClient.GetLogEvents(ctx, params)
attempts += 1
if err != nil {
if errors.As(err, &rnf) && attempts <= StandardRetries {
// The log group/stream hasn't been created yet, so wait and retry
time.Sleep(30 * time.Second)
continue
}
// if the error is not a ResourceNotFoundException, we should fail here.
return events, err
}
for _, e := range output.Events {
events = append(events, e)
}
if nextToken != nil && output.NextForwardToken != nil && *output.NextForwardToken == *nextToken {
// From the docs: If you have reached the end of the stream, it returns the same token you passed in.
log.Printf("Done paginating log events for %s/%s and found %d logs", logGroup, logStream, len(events))
break
}
nextToken = output.NextForwardToken
}
return events, nil
}
// IsLogGroupExists confirms whether the logGroupName exists or not
func IsLogGroupExists(logGroupName string, logGroupClassArg ...types.LogGroupClass) bool {
var logGroupClass types.LogGroupClass
if len(logGroupClassArg) > 0 {
logGroupClass = logGroupClassArg[0]
} else {
logGroupClass = types.LogGroupClassStandard
}
describeLogGroupInput := cloudwatchlogs.DescribeLogGroupsInput{
LogGroupNamePrefix: aws.String(logGroupName),
LogGroupClass: logGroupClass,
}
describeLogGroupOutput, err := CwlClient.DescribeLogGroups(ctx, &describeLogGroupInput)
if err != nil {
log.Println("error occurred while calling DescribeLogGroups", err)
return false
}
return len(describeLogGroupOutput.LogGroups) > 0
}
// GetLogQueryStats for the log group between start/end (in epoch seconds) for the
// query string.
func GetLogQueryStats(logGroupName string, startTime, endTime int64, queryString string) (*types.QueryStatistics, error) {
output, err := CwlClient.StartQuery(ctx, &cloudwatchlogs.StartQueryInput{
LogGroupName: aws.String(logGroupName),
StartTime: aws.Int64(startTime),
EndTime: aws.Int64(endTime),
QueryString: aws.String(queryString),
})
if err != nil {
return nil, fmt.Errorf("failed to start query for log group (%s): %w", logGroupName, err)
}
// Sleep a fixed amount of time after making the query to give it time to
// process the request.
time.Sleep(retryInterval)
var attempts int
for {
results, err := CwlClient.GetQueryResults(ctx, &cloudwatchlogs.GetQueryResultsInput{
QueryId: output.QueryId,
})
if err != nil {
return nil, fmt.Errorf("failed to get query results for log group (%s): %w", logGroupName, err)
}
switch results.Status {
case types.QueryStatusScheduled, types.QueryStatusRunning, types.QueryStatusUnknown:
if attempts >= StandardRetries {
return nil, fmt.Errorf("attempted get query results after %s without success. final status: %v", time.Duration(attempts)*retryInterval, results.Status)
}
attempts++
time.Sleep(retryInterval)
case types.QueryStatusComplete:
return results.Statistics, nil
default:
return nil, fmt.Errorf("unexpected query status: %v", results.Status)
}
}
}
// GetLogQueryResults for the log group between start/end (in epoch seconds) for the
// query string.
func GetLogQueryResults(logGroupName string, startTime, endTime int64, queryString string) ([][]types.ResultField, error) {
output, err := CwlClient.StartQuery(ctx, &cloudwatchlogs.StartQueryInput{
LogGroupName: aws.String(logGroupName),
StartTime: aws.Int64(startTime),
EndTime: aws.Int64(endTime),
QueryString: aws.String(queryString),
})
if err != nil {
return nil, fmt.Errorf("failed to start query for log group (%s): %w", logGroupName, err)
}
// Sleep a fixed amount of time after making the query to give it time to
// process the request.
time.Sleep(retryInterval)
var attempts int
for {
results, err := CwlClient.GetQueryResults(ctx, &cloudwatchlogs.GetQueryResultsInput{
QueryId: output.QueryId,
})
if err != nil {
return nil, fmt.Errorf("failed to get query results for log group (%s): %w", logGroupName, err)
}
switch results.Status {
case types.QueryStatusScheduled, types.QueryStatusRunning, types.QueryStatusUnknown:
if attempts >= StandardRetries {
return nil, fmt.Errorf("attempted get query results after %s without success. final status: %v", time.Duration(attempts)*retryInterval, results.Status)
}
attempts++
time.Sleep(retryInterval)
case types.QueryStatusComplete:
return results.Results, nil
default:
return nil, fmt.Errorf("unexpected query status: %v", results.Status)
}
}
}
func GetLogStreams(logGroupName string) []types.LogStream {
for i := 0; i < logStreamRetry; i++ {
describeLogStreamsOutput, err := CwlClient.DescribeLogStreams(ctx, &cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: aws.String(logGroupName),
OrderBy: types.OrderByLastEventTime,
Descending: aws.Bool(true),
Limit: aws.Int32(10),
})
if err != nil {
log.Printf("failed to get log streams for log group: %v - err: %v", logGroupName, err)
continue
}
if len(describeLogStreamsOutput.LogStreams) > 0 {
return describeLogStreamsOutput.LogStreams
}
time.Sleep(retryInterval)
}
return []types.LogStream{}
}
func GetLogStreamNames(logGroupName string) []string {
var logStreamNames []string
for _, stream := range GetLogStreams(logGroupName) {
logStreamNames = append(logStreamNames, *stream.LogStreamName)
}
return logStreamNames
}
type LogEventValidator func(event types.OutputLogEvent) error
type LogEventsValidator func(events []types.OutputLogEvent) error
type SchemaRetriever func(message string) (string, error)
func WithSchema(schema string) SchemaRetriever {
return func(_ string) (string, error) {
return schema, nil
}
}
func AssertLogSchema(schemaRetriever SchemaRetriever) LogEventValidator {
return func(event types.OutputLogEvent) error {
message := *event.Message
if schemaRetriever == nil {
return errors.New("nil schema retriever")
}
schema, err := schemaRetriever(*event.Message)
if err != nil {
return fmt.Errorf("unable to retrieve schema: %w", err)
}
keyErrors, err := jsonschema.Must(schema).ValidateBytes(context.Background(), []byte(message))
if err != nil {
return fmt.Errorf("failed to execute schema validator: %w", err)
} else if len(keyErrors) > 0 {
return fmt.Errorf("failed schema validation: %v | schema: %s | log: %s", keyErrors, schema, message)
}
return nil
}
}
func AssertLogContainsSubstring(substr string) LogEventValidator {
return func(event types.OutputLogEvent) error {
if !strings.Contains(*event.Message, substr) {
return fmt.Errorf("log event message missing substring (%s): %s", substr, *event.Message)
}
return nil
}
}
// AssertPerLog runs each validator on each of the log events. Fails fast.
func AssertPerLog(validators ...LogEventValidator) LogEventsValidator {
return func(events []types.OutputLogEvent) error {
for _, event := range events {
for _, validator := range validators {
if err := validator(event); err != nil {
return err
}
}
}
return nil
}
}
func AssertLogsNotEmpty() LogEventsValidator {
return func(events []types.OutputLogEvent) error {
if len(events) == 0 {
return errors.New("no log events")
}
return nil
}
}
func AssertLogsCount(count int) LogEventsValidator {
return func(events []types.OutputLogEvent) error {
if len(events) != count {
return fmt.Errorf("actual log events count (%v) does not match expected (%v)", len(events), count)
}
return nil
}
}
func AssertNoDuplicateLogs() LogEventsValidator {
return func(events []types.OutputLogEvent) error {
byTimestamp := make(map[int64]map[string]struct{})
for _, event := range events {
message := *event.Message
timestamp := *event.Timestamp
messages, ok := byTimestamp[timestamp]
if !ok {
messages = map[string]struct{}{}
byTimestamp[timestamp] = messages
}
_, ok = messages[message]
if ok {
return fmt.Errorf("duplicate message found at %v | message: %s", time.UnixMilli(timestamp), message)
}
messages[message] = struct{}{}
}
return nil
}
}
func GetLogEventCountPerType(logGroup, logStream string, since, until *time.Time) (map[string]int, error) {
var typeFrequency = make(map[string]int)
events, err := GetLogsSince(logGroup, logStream, since, until)
// if there is an error, return the empty map
if err != nil {
return typeFrequency, err
}
typeFrequency[NoLogTypeFound] = 0
for _, event := range events {
message := *event.Message
var eksClusterType EKSClusterType
innerErr := json.Unmarshal([]byte(message), &eksClusterType)
if innerErr != nil {
typeFrequency[NoLogTypeFound]++
}
typeFrequency[eksClusterType.Type]++
}
return typeFrequency, nil
}
func GetNeuronCoreUtilizationPerCore(logGroup, logStream string, since, until *time.Time) (map[string]float64, error) {
var coreUtilization = make(map[string]float64)
var data map[string]interface{}
events, err := GetLogsSince(logGroup, logStream, since, until)
// if there is an error, return the empty map
if err != nil {
return coreUtilization, err
}
for _, event := range events {
message := *event.Message
var eksClusterType EKSClusterType
innerErr := json.Unmarshal([]byte(message), &eksClusterType)
if innerErr != nil || !strings.Contains(eksClusterType.Type, "NodeAWSNeuronCore") {
continue
}
err := json.Unmarshal([]byte(message), &data)
if err != nil {
return coreUtilization, err
}
if core, ok := data["NeuronCore"].(string); ok {
if util, ok := data["node_neuroncore_utilization"].(float64); ok {
coreUtilization[core] = util
}
}
}
return coreUtilization, nil
}