-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
logs.go
360 lines (313 loc) · 10.1 KB
/
logs.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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package awscloudwatchreceiver // import "github.com/open-telemetry/opentelemetry-collector-contrib/receiver/awscloudwatchreceiver"
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudwatchlogs"
"go.opentelemetry.io/collector/component"
"go.opentelemetry.io/collector/consumer"
"go.opentelemetry.io/collector/pdata/pcommon"
"go.opentelemetry.io/collector/pdata/plog"
"go.uber.org/zap"
)
const (
noStreamName = "THIS IS INVALID STREAM"
)
type logsReceiver struct {
region string
profile string
imdsEndpoint string
pollInterval time.Duration
maxEventsPerRequest int
nextStartTime time.Time
groupRequests []groupRequest
autodiscover *AutodiscoverConfig
logger *zap.Logger
client client
consumer consumer.Logs
wg *sync.WaitGroup
doneChan chan bool
}
const maxLogGroupsPerDiscovery = int64(50)
type client interface {
DescribeLogGroupsWithContext(ctx context.Context, input *cloudwatchlogs.DescribeLogGroupsInput, opts ...request.Option) (*cloudwatchlogs.DescribeLogGroupsOutput, error)
FilterLogEventsWithContext(ctx context.Context, input *cloudwatchlogs.FilterLogEventsInput, opts ...request.Option) (*cloudwatchlogs.FilterLogEventsOutput, error)
}
type streamNames struct {
group string
names []*string
}
func (sn *streamNames) request(limit int, nextToken string, st, et *time.Time) *cloudwatchlogs.FilterLogEventsInput {
base := &cloudwatchlogs.FilterLogEventsInput{
LogGroupName: &sn.group,
StartTime: aws.Int64(st.UnixMilli()),
EndTime: aws.Int64(et.UnixMilli()),
Limit: aws.Int64(int64(limit)),
}
if len(sn.names) > 0 {
base.LogStreamNames = sn.names
}
if nextToken != "" {
base.NextToken = aws.String(nextToken)
}
return base
}
func (sn *streamNames) groupName() string {
return sn.group
}
type streamPrefix struct {
group string
prefix *string
}
func (sp *streamPrefix) request(limit int, nextToken string, st, et *time.Time) *cloudwatchlogs.FilterLogEventsInput {
base := &cloudwatchlogs.FilterLogEventsInput{
LogGroupName: &sp.group,
StartTime: aws.Int64(st.UnixMilli()),
EndTime: aws.Int64(et.UnixMilli()),
Limit: aws.Int64(int64(limit)),
LogStreamNamePrefix: sp.prefix,
}
if nextToken != "" {
base.NextToken = aws.String(nextToken)
}
return base
}
func (sp *streamPrefix) groupName() string {
return sp.group
}
type groupRequest interface {
request(limit int, nextToken string, st, et *time.Time) *cloudwatchlogs.FilterLogEventsInput
groupName() string
}
func newLogsReceiver(cfg *Config, logger *zap.Logger, consumer consumer.Logs) *logsReceiver {
groups := []groupRequest{}
for logGroupName, sc := range cfg.Logs.Groups.NamedConfigs {
for _, prefix := range sc.Prefixes {
groups = append(groups, &streamPrefix{group: logGroupName, prefix: prefix})
}
if len(sc.Names) > 0 {
groups = append(groups, &streamNames{group: logGroupName, names: sc.Names})
}
}
// safeguard from using both
autodiscover := cfg.Logs.Groups.AutodiscoverConfig
if len(cfg.Logs.Groups.NamedConfigs) > 0 {
autodiscover = nil
}
return &logsReceiver{
region: cfg.Region,
profile: cfg.Profile,
consumer: consumer,
maxEventsPerRequest: cfg.Logs.MaxEventsPerRequest,
imdsEndpoint: cfg.IMDSEndpoint,
autodiscover: autodiscover,
pollInterval: cfg.Logs.PollInterval,
nextStartTime: time.Now().Add(-cfg.Logs.PollInterval),
groupRequests: groups,
logger: logger,
wg: &sync.WaitGroup{},
doneChan: make(chan bool),
}
}
func (l *logsReceiver) Start(ctx context.Context, _ component.Host) error {
l.logger.Debug("starting to poll for Cloudwatch logs")
l.wg.Add(1)
go l.startPolling(ctx)
return nil
}
func (l *logsReceiver) Shutdown(_ context.Context) error {
l.logger.Debug("shutting down logs receiver")
close(l.doneChan)
l.wg.Wait()
return nil
}
func (l *logsReceiver) startPolling(ctx context.Context) {
defer l.wg.Done()
t := time.NewTicker(l.pollInterval)
for {
select {
case <-ctx.Done():
return
case <-l.doneChan:
return
case <-t.C:
if l.autodiscover != nil {
group, err := l.discoverGroups(ctx, l.autodiscover)
if err != nil {
l.logger.Error("unable to perform discovery of log groups", zap.Error(err))
continue
}
l.groupRequests = group
}
err := l.poll(ctx)
if err != nil {
l.logger.Error("there was an error during the poll", zap.Error(err))
}
}
}
}
func (l *logsReceiver) poll(ctx context.Context) error {
var errs error
startTime := l.nextStartTime
endTime := time.Now()
for _, r := range l.groupRequests {
if err := l.pollForLogs(ctx, r, startTime, endTime); err != nil {
errs = errors.Join(errs, err)
}
}
l.nextStartTime = endTime
return errs
}
func (l *logsReceiver) pollForLogs(ctx context.Context, pc groupRequest, startTime, endTime time.Time) error {
err := l.ensureSession()
if err != nil {
return err
}
nextToken := aws.String("")
for nextToken != nil {
select {
// if done, we want to stop processing paginated stream of events
case _, ok := <-l.doneChan:
if !ok {
return nil
}
default:
input := pc.request(l.maxEventsPerRequest, *nextToken, &startTime, &endTime)
resp, err := l.client.FilterLogEventsWithContext(ctx, input)
if err != nil {
l.logger.Error("unable to retrieve logs from cloudwatch", zap.String("log group", pc.groupName()), zap.Error(err))
break
}
observedTime := pcommon.NewTimestampFromTime(time.Now())
logs := l.processEvents(observedTime, pc.groupName(), resp)
if logs.LogRecordCount() > 0 {
if err = l.consumer.ConsumeLogs(ctx, logs); err != nil {
l.logger.Error("unable to consume logs", zap.Error(err))
break
}
}
nextToken = resp.NextToken
}
}
return nil
}
func (l *logsReceiver) processEvents(now pcommon.Timestamp, logGroupName string, output *cloudwatchlogs.FilterLogEventsOutput) plog.Logs {
logs := plog.NewLogs()
resourceMap := map[string](map[string]*plog.ResourceLogs){}
for _, e := range output.Events {
if e.Timestamp == nil {
l.logger.Error("unable to determine timestamp of event as the timestamp is nil")
continue
}
if e.EventId == nil {
l.logger.Error("no event ID was present on the event, skipping entry")
continue
}
if e.Message == nil {
l.logger.Error("no message was present on the event", zap.String("event.id", *e.EventId))
continue
}
group, ok := resourceMap[logGroupName]
if !ok {
group = map[string]*plog.ResourceLogs{}
resourceMap[logGroupName] = group
}
logStreamName := noStreamName
if e.LogStreamName != nil {
logStreamName = *e.LogStreamName
}
resourceLogs, ok := group[logStreamName]
if !ok {
rl := logs.ResourceLogs().AppendEmpty()
resourceLogs = &rl
resourceAttributes := resourceLogs.Resource().Attributes()
resourceAttributes.PutStr("aws.region", l.region)
resourceAttributes.PutStr("cloudwatch.log.group.name", logGroupName)
resourceAttributes.PutStr("cloudwatch.log.stream", logStreamName)
group[logStreamName] = resourceLogs
// Ensure one scopeLogs is initialized so we can handle in standardized way going forward.
_ = resourceLogs.ScopeLogs().AppendEmpty()
}
// Now we know resourceLogs is initialized and has one scopeLogs so we don't have to handle any special cases.
logRecord := resourceLogs.ScopeLogs().At(0).LogRecords().AppendEmpty()
logRecord.SetObservedTimestamp(now)
ts := time.UnixMilli(*e.Timestamp)
logRecord.SetTimestamp(pcommon.NewTimestampFromTime(ts))
logRecord.Body().SetStr(*e.Message)
logRecord.Attributes().PutStr("id", *e.EventId)
}
return logs
}
func (l *logsReceiver) discoverGroups(ctx context.Context, auto *AutodiscoverConfig) ([]groupRequest, error) {
l.logger.Debug("attempting to discover log groups.", zap.Int("limit", auto.Limit))
groups := []groupRequest{}
err := l.ensureSession()
if err != nil {
return groups, fmt.Errorf("unable to establish a session to auto discover log groups: %w", err)
}
numGroups := 0
var nextToken = aws.String("")
for nextToken != nil {
if numGroups >= auto.Limit {
break
}
req := &cloudwatchlogs.DescribeLogGroupsInput{
Limit: aws.Int64(maxLogGroupsPerDiscovery),
}
if auto.Prefix != "" {
req.LogGroupNamePrefix = &auto.Prefix
}
dlgResults, err := l.client.DescribeLogGroupsWithContext(ctx, req)
if err != nil {
return groups, fmt.Errorf("unable to list log groups: %w", err)
}
for _, lg := range dlgResults.LogGroups {
if numGroups == auto.Limit {
l.logger.Debug("reached limit of the number of log groups to discover."+
"To increase the number of groups able to be discovered, please increase the autodiscover limit field.",
zap.Int("groups_discovered", numGroups), zap.Int("limit", auto.Limit))
break
}
numGroups++
l.logger.Debug("discovered log group", zap.String("log group", lg.GoString()))
// default behavior is to collect all if not stream filtered
if len(auto.Streams.Names) == 0 && len(auto.Streams.Prefixes) == 0 {
groups = append(groups, &streamNames{group: *lg.LogGroupName})
continue
}
for _, prefix := range auto.Streams.Prefixes {
groups = append(groups, &streamPrefix{group: *lg.LogGroupName, prefix: prefix})
}
if len(auto.Streams.Names) > 0 {
groups = append(groups, &streamNames{group: *lg.LogGroupName, names: auto.Streams.Names})
}
}
nextToken = dlgResults.NextToken
}
return groups, nil
}
func (l *logsReceiver) ensureSession() error {
if l.client != nil {
return nil
}
awsConfig := aws.NewConfig().WithRegion(l.region)
options := session.Options{
Config: *awsConfig,
}
if l.imdsEndpoint != "" {
options.EC2IMDSEndpoint = l.imdsEndpoint
}
if l.profile != "" {
options.Profile = l.profile
}
s, err := session.NewSessionWithOptions(options)
l.client = cloudwatchlogs.New(s)
return err
}