/
output.go
375 lines (349 loc) · 11.2 KB
/
output.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
package cloudwatch
import (
"fmt"
"regexp"
"strings"
"sync"
"time"
"github.com/beaconsoftwarellc/gadget/v2/collection"
"github.com/beaconsoftwarellc/gadget/v2/timeutil"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
"github.com/beaconsoftwarellc/gadget/v2/dispatcher"
"github.com/beaconsoftwarellc/gadget/v2/errors"
"github.com/beaconsoftwarellc/gadget/v2/log"
"github.com/beaconsoftwarellc/gadget/v2/stringutil"
)
// 1 mebibyte is the actual max, but pad with a tenth so we don't have to be
// exact when calculating message size (int(1048576 * 0.9))
const (
defaultSendWait = 30 * time.Second
maxPayloadSizeBytes int = 943718
)
func newSession() (*session.Session, errors.TracerError) {
sess, err := session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
})
return sess, errors.Wrap(err)
}
type administration struct {
sync.Mutex
sendWait time.Duration
dispatcher dispatcher.Dispatcher
cwlogs *cloudwatchlogs.CloudWatchLogs
logGroups map[string]*cloudwatchlogs.LogGroup
logStreams map[string]*cloudwatchlogs.LogStream
// wrap destinations
outputs map[string]*output
}
// we only need one of these lazy initialized
var admin = &administration{
logGroups: make(map[string]*cloudwatchlogs.LogGroup),
logStreams: make(map[string]*cloudwatchlogs.LogStream),
outputs: make(map[string]*output),
}
// Administration provides a layer that manages the control of cloud watch logs to behave
// like a standard log output.
type Administration interface {
// GetOutput for the specified group and output name.
GetOutput(groupName, outputName string, logLevel log.LevelFlag) (log.Output, errors.TracerError)
}
// GetAdministration for cloud watch logs
func GetAdministration(logger log.Logger) (Administration, errors.TracerError) {
if nil != admin.cwlogs {
return admin, nil
}
sess, err := newSession()
if nil != err {
logger.Error(err)
return nil, err
}
admin.cwlogs = cloudwatchlogs.New(sess)
err = admin.UpdateLogGroups()
logger.Error(err)
return admin, errors.Wrap(err)
}
func (cwa *administration) Run(logger log.Logger) {
cwa.Lock()
defer cwa.Unlock()
timeutil.RunEvery(func() {
for _, output := range cwa.outputs {
logger.Error(output.SendEvents(logger))
}
}, cwa.sendWait)
}
func createStreamKey(groupName, streamName string) string {
groupName = EnsureGroupNameIsValid(groupName)
streamName = EnsureStreamNameIsValid(streamName)
return fmt.Sprintf("%s.%s", groupName, streamName)
}
// UpdateLogGroups pulls all the existing log groups from CloudWatch and adds
// them to this instance so that they might be used.
// NOTE: We should not have a ton of log groups so holding all of them in memory
// should not be a big deal. The standard maximum number of log groups in AWS
// is 5000.
func (cwa *administration) UpdateLogGroups() errors.TracerError {
cwa.Lock()
defer cwa.Unlock()
var nextToken string
var err error
var input *cloudwatchlogs.DescribeLogGroupsInput
var output *cloudwatchlogs.DescribeLogGroupsOutput
var limit int64 = 50
for {
if stringutil.IsWhiteSpace(nextToken) {
input = &cloudwatchlogs.DescribeLogGroupsInput{
Limit: &limit,
}
} else {
input = &cloudwatchlogs.DescribeLogGroupsInput{
Limit: &limit,
NextToken: &nextToken,
}
}
output, err = cwa.cwlogs.DescribeLogGroups(input)
if nil != err {
break
}
for _, group := range output.LogGroups {
cwa.logGroups[*group.LogGroupName] = group
}
if len(output.LogGroups) < int(limit) || nil == output.NextToken || stringutil.IsWhiteSpace(*output.NextToken) {
break
}
nextToken = *output.NextToken
}
return errors.Wrap(err)
}
func (cwa *administration) GetOutput(groupName, streamName string, logLevel log.LevelFlag) (log.Output, errors.TracerError) {
var err error
// get the log group
group, err := cwa.GetLogGroup(groupName)
if nil != err {
return nil, errors.Wrap(err)
}
// now for the stream
streamName = EnsureStreamNameIsValid(streamName)
outputKey := createStreamKey(*group.LogGroupName, streamName)
logOutput, ok := cwa.outputs[outputKey]
if !ok {
stream, err := cwa.GetLogStream(group, streamName)
if nil != err {
return nil, errors.Wrap(err)
}
// we are gtg
logOutput = &output{
name: createStreamKey(*group.LogGroupName, *stream.LogStreamName),
group: group,
stream: stream,
logLevel: logLevel,
admin: cwa,
buffer: collection.NewQueue[*cloudwatchlogs.InputLogEvent](),
}
}
return logOutput, errors.Wrap(err)
}
func (cwa *administration) GetLogGroup(groupName string) (*cloudwatchlogs.LogGroup, errors.TracerError) {
groupName = EnsureGroupNameIsValid(groupName)
var err error
cwa.Lock()
group, ok := cwa.logGroups[groupName]
cwa.Unlock()
if ok {
return group, nil
}
// it does not exist as far as we can tell so try creation
input := &cloudwatchlogs.CreateLogGroupInput{
LogGroupName: &groupName,
// we can put tags here as well as needed
}
// the response from this is a marker so we do not need it.
_, err = cwa.cwlogs.CreateLogGroup(input)
if nil != err {
// error handling, return error unless it is an 'already exists' which means we just
// didn't know about it yet
if err, ok := err.(awserr.Error); !ok || err.Code() != cloudwatchlogs.ErrCodeResourceAlreadyExistsException {
return nil, errors.Wrap(err)
}
}
// update to bring it into the fold
err = cwa.UpdateLogGroups()
if nil != err {
return nil, errors.Wrap(err)
}
cwa.Lock()
group, ok = cwa.logGroups[groupName]
cwa.Unlock()
if !ok {
return nil, errors.New("could not create or find cloud watch logs log group %s", groupName)
}
// if creation fails as existing try an update
return group, errors.Wrap(err)
}
func (cwa *administration) GetLogStream(group *cloudwatchlogs.LogGroup, streamName string) (*cloudwatchlogs.LogStream, errors.TracerError) {
streamName = EnsureStreamNameIsValid(streamName)
var err error
streamKey := createStreamKey(*group.LogGroupName, streamName)
cwa.Lock()
stream, ok := cwa.logStreams[streamKey]
cwa.Unlock()
if ok {
return stream, nil
}
input := &cloudwatchlogs.CreateLogStreamInput{
LogGroupName: group.LogGroupName,
LogStreamName: &streamName,
}
// return is a marker value which can be ignored.
_, err = cwa.cwlogs.CreateLogStream(input)
if nil != err {
if err, ok := err.(awserr.Error); !ok || err.Code() != cloudwatchlogs.ErrCodeResourceAlreadyExistsException {
return nil, errors.Wrap(err)
}
}
// now actually get the damn thing
stream, err = cwa.FindLogStream(*group.LogGroupName, streamName)
if nil != err {
return nil, errors.Wrap(err)
}
// add the reference to our map
cwa.Lock()
cwa.logStreams[streamKey] = stream
cwa.Unlock()
return stream, errors.Wrap(err)
}
func (cwa *administration) UpdateLogStream(groupName, streamName string, logger log.Logger) {
streamKey := createStreamKey(groupName, streamName)
stream, err := cwa.FindLogStream(groupName, streamName)
if nil != err {
logger.Errorf("failed to update log stream: %s", err)
}
cwa.Lock()
s, ok := cwa.logStreams[streamKey]
if ok {
// do not replace or existing tasks will lose their reference.
s.SetUploadSequenceToken(*stream.UploadSequenceToken)
} else {
// this would be weird, but handle it just in case
cwa.logStreams[streamKey] = stream
}
cwa.Unlock()
}
func (cwa *administration) FindLogStream(groupName, streamName string) (*cloudwatchlogs.LogStream, errors.TracerError) {
groupName = EnsureGroupNameIsValid(groupName)
streamName = EnsureStreamNameIsValid(streamName)
input := &cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: &groupName,
LogStreamNamePrefix: &streamName,
}
output, err := cwa.cwlogs.DescribeLogStreams(input)
if nil != err {
return nil, errors.Wrap(err)
}
for _, stream := range output.LogStreams {
if *stream.LogStreamName == streamName {
// we are not locking so don't update anything here
return stream, nil
}
}
return nil, errors.New("failed to locate log stream '%s' in log group '%s'", streamName, groupName)
}
// output is a wrapper for a log stream that we can attach our interface methods to.
type output struct {
sync.Mutex
name string
admin *administration
logLevel log.LevelFlag
group *cloudwatchlogs.LogGroup
stream *cloudwatchlogs.LogStream
buffer collection.Queue[*cloudwatchlogs.InputLogEvent]
// token is unique to the stream and must be set to sequence the events correctly
token *string
}
func (o *output) Level() log.LevelFlag {
return o.logLevel
}
func (o *output) Log(message log.Message) {
o.Lock()
defer o.Unlock()
payload := message.JSONString()
// they want milliseconds since epoch and our timestamps are in seconds.
ts := message.TimestampUnix * 1000
o.buffer.Push(&cloudwatchlogs.InputLogEvent{
Message: &payload,
Timestamp: &ts,
})
}
func (o *output) SendEvents(logger log.Logger) error {
o.Lock()
defer o.Unlock()
if o.buffer.Size() == 0 {
return nil
}
events := make([]*cloudwatchlogs.InputLogEvent, 0)
sizeBytes := 0
for o.buffer.Size() > 0 {
event, err := o.buffer.Peek()
if nil != err {
break
}
if sizeBytes+len([]byte(*event.Message)) > maxPayloadSizeBytes {
break
}
// actually pop it now
o.buffer.Pop()
events = append(events, event)
}
if len(events) == 0 {
return nil
}
input := &cloudwatchlogs.PutLogEventsInput{
LogEvents: events,
LogGroupName: o.group.LogGroupName,
LogStreamName: o.stream.LogStreamName,
SequenceToken: o.stream.UploadSequenceToken,
}
resp, err := o.admin.cwlogs.PutLogEvents(input)
if err == nil {
o.stream = o.stream.SetUploadSequenceToken(*resp.NextSequenceToken)
}
if awsErr, ok := err.(awserr.Error); !ok || awsErr.Code() != cloudwatchlogs.ErrCodeInvalidSequenceTokenException {
// our sequence token got out of data so refresh it
o.admin.UpdateLogStream(*o.group.LogGroupName, *o.stream.LogStreamName, logger)
// don't log this error
err = nil
} else if nil != err {
logger.Error(err)
}
// if we still have events run again
if o.buffer.Size() > 0 && nil == err {
return o.SendEvents(logger)
}
return err
}
var groupNameRegex = regexp.MustCompile("[^a-zA-Z0-9_\\-/.]+")
// EnsureGroupNameIsValid based upon the rules from aws:
// - Log group names must be unique within a region for an AWS account.
// - Log group names can be between 1 and 512 characters long.
// - Log group names consist of the following characters: a-z, A-Z, 0-9,
// '_' (underscore), '-' (hyphen), '/' (forward slash), and '.' (period).
func EnsureGroupNameIsValid(name string) string {
validName := groupNameRegex.ReplaceAllString(name, "")
if stringutil.IsWhiteSpace(validName) {
validName = "EmptyLogGroupName"
}
return stringutil.SafeSubstring(validName, 0, 511)
}
// EnsureStreamNameIsValid based upon the provided rules from AWS
// - Log stream names must be unique within the log group.
// - Log stream names can be between 1 and 512 characters long.
// - The ':' (colon) and '*' (asterisk) characters are not allowed.
func EnsureStreamNameIsValid(name string) string {
validName := strings.Replace(name, ":", "", -1)
validName = strings.Replace(validName, "*", "", -1)
if stringutil.IsWhiteSpace(validName) {
validName = "EmptyLogStreamName"
}
return stringutil.SafeSubstring(validName, 0, 511)
}