-
Notifications
You must be signed in to change notification settings - Fork 391
/
cloudwatchlogs.go
175 lines (156 loc) · 5.49 KB
/
cloudwatchlogs.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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
// Package cloudwatchlogs provides a client to make API requests to Amazon CloudWatch Logs.
package cloudwatchlogs
import (
"fmt"
"sort"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
)
const (
// SleepDuration is the sleep time for making the next request for log events.
SleepDuration = 1 * time.Second
logStreamNamePrefix = "copilot/"
)
var (
fatalCodes = []string{"FATA", "FATAL", "fatal", "ERR", "ERROR", "error"}
warningCodes = []string{"WARN", "warn", "WARNING", "warning"}
)
type api interface {
DescribeLogStreams(input *cloudwatchlogs.DescribeLogStreamsInput) (*cloudwatchlogs.DescribeLogStreamsOutput, error)
GetLogEvents(input *cloudwatchlogs.GetLogEventsInput) (*cloudwatchlogs.GetLogEventsOutput, error)
}
// CloudWatchLogs wraps an AWS Cloudwatch Logs client.
type CloudWatchLogs struct {
client api
}
// GetLogEventsOpts sets up optional parameters for LogEvents function.
type GetLogEventsOpts func(*cloudwatchlogs.GetLogEventsInput)
// WithLimit sets up limit for GetLogEventsInput
func WithLimit(limit int) GetLogEventsOpts {
return func(in *cloudwatchlogs.GetLogEventsInput) {
in.Limit = aws.Int64(int64(limit))
}
}
// WithStartTime sets up startTime for GetLogEventsInput
func WithStartTime(startTime int64) GetLogEventsOpts {
return func(in *cloudwatchlogs.GetLogEventsInput) {
in.StartTime = aws.Int64(startTime)
}
}
// WithEndTime sets up endTime for GetLogEventsInput
func WithEndTime(endTime int64) GetLogEventsOpts {
return func(in *cloudwatchlogs.GetLogEventsInput) {
in.EndTime = aws.Int64(endTime)
}
}
// LogEventsOutput contains the output for LogEvents
type LogEventsOutput struct {
// Retrieved log events.
Events []*Event
// Timestamp for the last event
LastEventTime map[string]int64
}
// New returns a CloudWatchLogs configured against the input session.
func New(s *session.Session) *CloudWatchLogs {
return &CloudWatchLogs{
client: cloudwatchlogs.New(s),
}
}
// logStreams returns all name of the log streams in a log group.
func (c *CloudWatchLogs) logStreams(logGroupName string) ([]*string, error) {
resp, err := c.client.DescribeLogStreams(&cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: aws.String(logGroupName),
Descending: aws.Bool(true),
OrderBy: aws.String(cloudwatchlogs.OrderByLastEventTime),
})
if err != nil {
return nil, fmt.Errorf("describe log streams of log group %s: %w", logGroupName, err)
}
if len(resp.LogStreams) == 0 {
return nil, fmt.Errorf("no log stream found in log group %s", logGroupName)
}
logStreamNames := make([]*string, len(resp.LogStreams))
for ind, logStream := range resp.LogStreams {
logStreamNames[ind] = logStream.LogStreamName
}
return logStreamNames, nil
}
// TaskLogEvents returns an array of Cloudwatch Logs events.
func (c *CloudWatchLogs) TaskLogEvents(logGroupName string, streamLastEventTime map[string]int64, opts ...GetLogEventsOpts) (*LogEventsOutput, error) {
var events []*Event
var in *cloudwatchlogs.GetLogEventsInput
logStreamNames, err := c.logStreams(logGroupName)
if err != nil {
return nil, err
}
for _, logStreamName := range logStreamNames {
in = &cloudwatchlogs.GetLogEventsInput{
LogGroupName: aws.String(logGroupName),
LogStreamName: logStreamName,
Limit: aws.Int64(10), // default to be 10
}
for _, opt := range opts {
opt(in)
}
if streamLastEventTime[*logStreamName] != 0 {
// If last event for this log stream exists, increment last log event timestamp
// by one to get logs after the last event.
in.SetStartTime(streamLastEventTime[*logStreamName] + 1)
}
// TODO: https://github.com/aws/amazon-ecs-cli-v2/pull/628#discussion_r374291068 and https://github.com/aws/amazon-ecs-cli-v2/pull/628#discussion_r374294362
resp, err := c.client.GetLogEvents(in)
if err != nil {
return nil, fmt.Errorf("get log events of %s/%s: %w", logGroupName, *logStreamName, err)
}
for _, event := range resp.Events {
log := &Event{
LogStreamName: trimLogStreamName(*logStreamName),
IngestionTime: aws.Int64Value(event.IngestionTime),
Message: aws.StringValue(event.Message),
Timestamp: aws.Int64Value(event.Timestamp),
}
events = append(events, log)
}
if len(resp.Events) != 0 {
streamLastEventTime[*logStreamName] = *resp.Events[len(resp.Events)-1].Timestamp
}
}
sort.SliceStable(events, func(i, j int) bool { return events[i].Timestamp < events[j].Timestamp })
var truncatedEvents []*Event
if len(events) >= int(*in.Limit) {
truncatedEvents = events[len(events)-int(*in.Limit):]
} else {
truncatedEvents = events
}
return &LogEventsOutput{
Events: truncatedEvents,
LastEventTime: streamLastEventTime,
}, nil
}
// LogGroupExists returns if a log group exists.
func (c *CloudWatchLogs) LogGroupExists(logGroupName string) (bool, error) {
_, err := c.client.DescribeLogStreams(&cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: aws.String(logGroupName),
})
if err == nil {
return true, nil
}
aerr, ok := err.(awserr.Error)
if !ok {
return false, err
}
if aerr.Code() != cloudwatchlogs.ErrCodeResourceNotFoundException {
return false, err
}
return false, nil
}
func trimLogStreamName(logStreamName string) string {
// logStreamName example: copilot/{name}/1cc0685ad01d4d0f8e4e2c00d1775c56
return strings.TrimPrefix(logStreamName, logStreamNamePrefix)
}