-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathexporter.go
243 lines (220 loc) · 7.09 KB
/
exporter.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
// Copyright 2020, OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package awscloudwatchlogsexporter
import (
"context"
"encoding/json"
"errors"
"fmt"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"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/model/pdata"
"go.uber.org/zap"
)
type exporter struct {
config *Config
logger *zap.Logger
startOnce sync.Once
client *cloudwatchlogs.CloudWatchLogs // available after startOnce
seqTokenMu sync.Mutex
seqToken string
}
func (e *exporter) Start(ctx context.Context, host component.Host) error {
var startErr error
e.startOnce.Do(func() {
awsConfig := &aws.Config{}
if e.config.Region != "" {
awsConfig.Region = aws.String(e.config.Region)
}
if e.config.Endpoint != "" {
awsConfig.Endpoint = aws.String(e.config.Endpoint)
}
awsConfig.MaxRetries = aws.Int(1) // retry will be handled by the collector queue
sess, err := session.NewSession(awsConfig)
if err != nil {
startErr = err
return
}
e.client = cloudwatchlogs.New(sess)
e.logger.Debug("Retrieving CloudWatch sequence token")
out, err := e.client.DescribeLogStreams(&cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: aws.String(e.config.LogGroupName),
LogStreamNamePrefix: aws.String(e.config.LogStreamName),
})
if err != nil {
startErr = err
return
}
if len(out.LogStreams) == 0 {
startErr = errors.New("cannot find log group and stream")
return
}
stream := out.LogStreams[0]
if stream.UploadSequenceToken == nil {
e.logger.Debug("CloudWatch sequence token is nil, will assume empty")
return
}
e.seqToken = *stream.UploadSequenceToken
})
return startErr
}
func (e *exporter) Shutdown(ctx context.Context) error {
// TODO(jbd): Signal shutdown to flush the logs.
return nil
}
func (e *exporter) PushLogs(ctx context.Context, ld pdata.Logs) (err error) {
// TODO(jbd): Relax this once CW Logs support ingest
// without sequence tokens.
e.seqTokenMu.Lock()
defer e.seqTokenMu.Unlock()
logEvents, _ := logsToCWLogs(e.logger, ld)
if len(logEvents) == 0 {
return nil
}
e.logger.Debug("Putting log events", zap.Int("num_of_events", len(logEvents)))
input := &cloudwatchlogs.PutLogEventsInput{
LogGroupName: aws.String(e.config.LogGroupName),
LogStreamName: aws.String(e.config.LogStreamName),
LogEvents: logEvents,
}
if e.seqToken != "" {
input.SequenceToken = aws.String(e.seqToken)
} else {
e.logger.Debug("Putting log events without a sequence token")
}
out, err := e.client.PutLogEvents(input)
if err != nil {
return err
}
if info := out.RejectedLogEventsInfo; info != nil {
return fmt.Errorf("log event rejected: %s", info.String())
}
e.logger.Debug("Log events are successfully put")
e.seqToken = *out.NextSequenceToken
return nil
}
func logsToCWLogs(logger *zap.Logger, ld pdata.Logs) ([]*cloudwatchlogs.InputLogEvent, int) {
n := ld.ResourceLogs().Len()
if n == 0 {
return []*cloudwatchlogs.InputLogEvent{}, 0
}
var dropped int
out := make([]*cloudwatchlogs.InputLogEvent, 0) // TODO(jbd): set a better capacity
rls := ld.ResourceLogs()
for i := 0; i < rls.Len(); i++ {
rl := rls.At(i)
resourceAttrs := attrsValue(rl.Resource().Attributes())
ills := rl.InstrumentationLibraryLogs()
for j := 0; j < ills.Len(); j++ {
ils := ills.At(j)
logs := ils.Logs()
for k := 0; k < logs.Len(); k++ {
log := logs.At(k)
event, err := logToCWLog(resourceAttrs, log)
if err != nil {
logger.Debug("Failed to convert to CloudWatch Log", zap.Error(err))
dropped++
} else {
out = append(out, event)
}
}
}
}
return out, dropped
}
type cwLogBody struct {
Name string `json:"name,omitempty"`
Body interface{} `json:"body,omitempty"`
SeverityNumber int32 `json:"severity_number,omitempty"`
SeverityText string `json:"severity_text,omitempty"`
DroppedAttributesCount uint32 `json:"dropped_attributes_count,omitempty"`
Flags uint32 `json:"flags,omitempty"`
TraceID string `json:"trace_id,omitempty"`
SpanID string `json:"span_id,omitempty"`
Attributes map[string]interface{} `json:"attributes,omitempty"`
Resource map[string]interface{} `json:"resource,omitempty"`
}
func logToCWLog(resourceAttrs map[string]interface{}, log pdata.LogRecord) (*cloudwatchlogs.InputLogEvent, error) {
// TODO(jbd): Benchmark and improve the allocations.
// Evaluate go.elastic.co/fastjson as a replacement for encoding/json.
body := cwLogBody{
Name: log.Name(),
Body: attrValue(log.Body()),
SeverityNumber: int32(log.SeverityNumber()),
SeverityText: log.SeverityText(),
DroppedAttributesCount: log.DroppedAttributesCount(),
Flags: log.Flags(),
}
if traceID := log.TraceID(); !traceID.IsEmpty() {
body.TraceID = traceID.HexString()
}
if spanID := log.SpanID(); !spanID.IsEmpty() {
body.SpanID = spanID.HexString()
}
body.Attributes = attrsValue(log.Attributes())
body.Resource = resourceAttrs
bodyJSON, err := json.Marshal(body)
if err != nil {
return nil, err
}
return &cloudwatchlogs.InputLogEvent{
Timestamp: aws.Int64(int64(log.Timestamp()) / int64(time.Millisecond)), // in milliseconds
Message: aws.String(string(bodyJSON)),
}, nil
}
func attrsValue(attrs pdata.AttributeMap) map[string]interface{} {
if attrs.Len() == 0 {
return nil
}
out := make(map[string]interface{}, attrs.Len())
attrs.Range(func(k string, v pdata.AttributeValue) bool {
out[k] = attrValue(v)
return true
})
return out
}
func attrValue(value pdata.AttributeValue) interface{} {
switch value.Type() {
case pdata.AttributeValueTypeInt:
return value.IntVal()
case pdata.AttributeValueTypeBool:
return value.BoolVal()
case pdata.AttributeValueTypeDouble:
return value.DoubleVal()
case pdata.AttributeValueTypeString:
return value.StringVal()
case pdata.AttributeValueTypeMap:
values := map[string]interface{}{}
value.MapVal().Range(func(k string, v pdata.AttributeValue) bool {
values[k] = attrValue(v)
return true
})
return values
case pdata.AttributeValueTypeArray:
arrayVal := value.ArrayVal()
values := make([]interface{}, arrayVal.Len())
for i := 0; i < arrayVal.Len(); i++ {
values[i] = attrValue(arrayVal.At(i))
}
return values
case pdata.AttributeValueTypeNull:
return nil
default:
return nil
}
}