-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathuploader.go
200 lines (185 loc) · 5.48 KB
/
uploader.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
package cloudwatch
import (
"errors"
"fmt"
"log"
"os"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
)
// CloudwatchUploader receieves CloudwatchBatches on its input channel,
// and sends them on to the AWS Cloudwatch Logs endpoint.
type CloudwatchUploader struct {
Input chan CloudwatchBatch
svc *cloudwatchlogs.CloudWatchLogs
tokens map[string]string
debugSet bool
}
func NewCloudwatchUploader(adapter *CloudwatchAdapter) *CloudwatchUploader {
region := adapter.Route.Address
if (region == "auto") || (region == "") {
if adapter.Ec2Region == "" {
log.Println("cloudwatch: ERROR - could not get region from EC2")
} else {
region = adapter.Ec2Region
}
}
debugSet := false
_, debugOption := adapter.Route.Options[`DEBUG`]
if debugOption || (os.Getenv(`DEBUG`) != "") {
debugSet = true
log.Println("cloudwatch: Creating AWS Cloudwatch client for region",
region)
}
uploader := CloudwatchUploader{
Input: make(chan CloudwatchBatch),
tokens: map[string]string{},
debugSet: debugSet,
svc: cloudwatchlogs.New(session.New(),
&aws.Config{Region: aws.String(region)}),
}
go uploader.Start()
return &uploader
}
// Main loop for the Uploader - POSTs each batch to AWS Cloudwatch Logs,
// while keeping track of the unique sequence token for each log stream.
func (u *CloudwatchUploader) Start() {
for batch := range u.Input {
msg := batch.Msgs[0]
u.log("Submitting batch for %s-%s (length %d, size %v)",
msg.Group, msg.Stream, len(batch.Msgs), batch.Size)
// fetch and cache the upload sequence token
var token *string
if cachedToken, isCached := u.tokens[msg.Container]; isCached {
token = &cachedToken
u.log("Got token from cache: %s", *token)
} else {
u.log("Fetching token from AWS...")
awsToken, err := u.getSequenceToken(msg)
if err != nil {
u.log("ERROR:", err)
continue
}
if awsToken != nil {
u.tokens[msg.Container] = *(awsToken)
u.log("Got token from AWS:", *awsToken)
token = awsToken
}
}
// generate the array of InputLogEvent from the batch's contents
events := []*cloudwatchlogs.InputLogEvent{}
for _, msg := range batch.Msgs {
event := cloudwatchlogs.InputLogEvent{
Message: aws.String(msg.Message),
Timestamp: aws.Int64(msg.Time.UnixNano() / 1000000),
}
events = append(events, &event)
}
params := &cloudwatchlogs.PutLogEventsInput{
LogEvents: events,
LogGroupName: aws.String(msg.Group),
LogStreamName: aws.String(msg.Stream),
SequenceToken: token,
}
u.log("POSTing PutLogEvents to %s-%s with %d messages, %d bytes",
msg.Group, msg.Stream, len(batch.Msgs), batch.Size)
resp, err := u.svc.PutLogEvents(params)
if err != nil {
u.log(err.Error())
continue
}
u.log("Got 200 response")
if resp.NextSequenceToken != nil {
u.log("Caching new sequence token for %s-%s: %s",
msg.Group, msg.Stream, *resp.NextSequenceToken)
u.tokens[msg.Container] = *resp.NextSequenceToken
}
}
}
// AWS CLIENT METHODS
// returns the next sequence token for the log stream associated
// with the given message's group and stream. Creates the stream as needed.
func (u *CloudwatchUploader) getSequenceToken(msg CloudwatchMessage) (*string,
error) {
group, stream := msg.Group, msg.Stream
groupExists, err := u.groupExists(group)
if err != nil {
return nil, err
}
if !groupExists {
err = u.createGroup(group)
if err != nil {
return nil, err
}
}
params := &cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: aws.String(group),
LogStreamNamePrefix: aws.String(stream),
}
u.log("Describing stream %s-%s...", group, stream)
resp, err := u.svc.DescribeLogStreams(params)
if err != nil {
return nil, err
}
if count := len(resp.LogStreams); count > 1 { // too many matching streams!
return nil, errors.New(fmt.Sprintf(
"%d streams match group %s, stream %s!", count, group, stream))
}
if len(resp.LogStreams) == 0 { // no matching streams - create one and retry
if err = u.createStream(group, stream); err != nil {
return nil, err
}
token, err := u.getSequenceToken(msg)
return token, err
}
return resp.LogStreams[0].UploadSequenceToken, nil
}
func (u *CloudwatchUploader) groupExists(group string) (bool, error) {
u.log("Checking for group: %s...", group)
resp, err := u.svc.DescribeLogGroups(&cloudwatchlogs.DescribeLogGroupsInput{
LogGroupNamePrefix: aws.String(group),
})
if err != nil {
return false, err
}
for _, matchedGroup := range resp.LogGroups {
if *matchedGroup.LogGroupName == group {
return true, nil
}
}
return false, nil
}
func (u *CloudwatchUploader) createGroup(group string) error {
u.log("Creating group: %s...", group)
params := &cloudwatchlogs.CreateLogGroupInput{
LogGroupName: aws.String(group),
}
if _, err := u.svc.CreateLogGroup(params); err != nil {
return err
}
return nil
}
func (u *CloudwatchUploader) createStream(group, stream string) error {
u.log("Creating stream for group %s, stream %s...", group, stream)
params := &cloudwatchlogs.CreateLogStreamInput{
LogGroupName: aws.String(group),
LogStreamName: aws.String(stream),
}
if _, err := u.svc.CreateLogStream(params); err != nil {
return err
}
return nil
}
// HELPER METHODS
func (u *CloudwatchUploader) log(format string, args ...interface{}) {
if u.debugSet {
msg := fmt.Sprintf(format, args...)
msg = fmt.Sprintf("cloudwatch: %s", msg)
if !strings.HasSuffix(msg, "\n") {
msg = fmt.Sprintf("%s\n", msg)
}
log.Print(msg)
}
}