-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathout_cloudwatch_logs.go
368 lines (311 loc) · 10.3 KB
/
out_cloudwatch_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
361
362
363
364
365
366
367
368
package main
import "github.com/fluent/fluent-bit-go/output"
import "github.com/json-iterator/go"
import "github.com/aws/aws-sdk-go/aws"
import "github.com/aws/aws-sdk-go/aws/awserr"
import "github.com/aws/aws-sdk-go/service/cloudwatchlogs"
import "github.com/aws/aws-sdk-go/aws/session"
import (
"C"
"fmt"
"os"
"time"
"unsafe"
)
var plugin GoOutputPlugin = &fluentPlugin{}
var cloudwatchLogs *cloudwatchlogs.CloudWatchLogs
type cloudWatchLogsConf struct {
logGroupName string
logStreamName string
autoCreateStream bool
}
type updateToken struct {
logGroup string
logStream string
}
var configCtx *cloudWatchLogsConf
var sequenceTokensCtx map[updateToken]string
type GoOutputPlugin interface {
PluginConfigKey(ctx unsafe.Pointer, key string) string
Unregister(ctx unsafe.Pointer)
GetRecord(dec *output.FLBDecoder) (ret int, ts interface{}, rec map[interface{}]interface{})
NewDecoder(data unsafe.Pointer, length int) *output.FLBDecoder
Put(logEvents []*cloudwatchlogs.InputLogEvent, sequenceToken string) (*cloudwatchlogs.PutLogEventsOutput, error)
CheckLogGroupsExistence(logGroupName string) bool
CheckLogStreamsExistence(logGroupName, logStreamName string) (bool, string)
CreateLogGroup(logGroupName string) error
CreateLogStream(logGroupName, logStreamName string) error
Exit(code int)
}
type fluentPlugin struct{}
func (p *fluentPlugin) PluginConfigKey(ctx unsafe.Pointer, key string) string {
return output.FLBPluginConfigKey(ctx, key)
}
func (p *fluentPlugin) Unregister(ctx unsafe.Pointer) {
output.FLBPluginUnregister(ctx)
}
func (p *fluentPlugin) GetRecord(dec *output.FLBDecoder) (int, interface{}, map[interface{}]interface{}) {
return output.GetRecord(dec)
}
func (p *fluentPlugin) NewDecoder(data unsafe.Pointer, length int) *output.FLBDecoder {
return output.NewDecoder(data, int(length))
}
func (p *fluentPlugin) Exit(code int) {
os.Exit(code)
}
func (p *fluentPlugin) Put(logEvents []*cloudwatchlogs.InputLogEvent, sequenceToken string) (*cloudwatchlogs.PutLogEventsOutput, error) {
params := &cloudwatchlogs.PutLogEventsInput{
LogEvents: logEvents,
LogGroupName: aws.String(configCtx.logGroupName), // Mandatory
LogStreamName: aws.String(configCtx.logStreamName), // Mandatory
}
if sequenceToken != "" {
params.SequenceToken = aws.String(sequenceToken)
}
resp, err := cloudwatchLogs.PutLogEvents(params)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Get error details
fmt.Println("Error:", awsErr.Code(), awsErr.Message())
// Prints out full error message, including original error if there was one.
fmt.Println("Error:", awsErr.Error())
return nil, err
} else if err != nil {
// A non-service error occurred.
// A service error occurred.
fmt.Printf("Fatal: %v\n", err)
return nil, err
}
}
return resp, nil
}
func (p *fluentPlugin) CheckLogGroupsExistence(logGroupName string) bool {
params := &cloudwatchlogs.DescribeLogGroupsInput{
LogGroupNamePrefix: aws.String(logGroupName), // Required
}
resp, err := cloudwatchLogs.DescribeLogGroups(params)
if err != nil {
fmt.Printf("Error: %v\n", err)
return false
}
logGroups := resp.LogGroups
for _, logGroup := range logGroups {
if logGroupName == *logGroup.LogGroupName {
return true
}
}
return false
}
func (p *fluentPlugin) CheckLogStreamsExistence(logGroupName, logStreamName string) (bool, string) {
params := &cloudwatchlogs.DescribeLogStreamsInput{
LogGroupName: aws.String(logGroupName),
LogStreamNamePrefix: aws.String(logStreamName), // Required
}
resp, err := cloudwatchLogs.DescribeLogStreams(params)
if err != nil {
fmt.Printf("Error: %v\n", err)
return false, ""
}
logStreams := resp.LogStreams
for _, logStream := range logStreams {
if logStreamName == *logStream.LogStreamName {
nextToken := *logStream.UploadSequenceToken
if nextToken != "" {
return true, nextToken
} else {
return false, ""
}
}
}
return false, ""
}
func (p *fluentPlugin) CreateLogGroup(logGroupName string) error {
params := &cloudwatchlogs.CreateLogGroupInput{
LogGroupName: aws.String(logGroupName), // Required
}
_, err := cloudwatchLogs.CreateLogGroup(params)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Get error details
fmt.Println("Error:", awsErr.Code(), awsErr.Message())
// Prints out full error message, including original error if there was one.
fmt.Println("Error:", awsErr.Error())
return err
} else if err != nil {
// A non-service error occurred.
// A service error occurred.
fmt.Printf("Fatal: %v\n", err)
return err
}
}
return nil
}
func (p *fluentPlugin) CreateLogStream(logGroupName, logStreamName string) error {
params := &cloudwatchlogs.CreateLogStreamInput{
LogGroupName: aws.String(logGroupName), // Required
LogStreamName: aws.String(logStreamName), // Required
}
_, err := cloudwatchLogs.CreateLogStream(params)
if err != nil {
if awsErr, ok := err.(awserr.Error); ok {
// Get error details
fmt.Println("Error:", awsErr.Code(), awsErr.Message())
// Prints out full error message, including original error if there was one.
fmt.Println("Error:", awsErr.Error())
return err
} else if err != nil {
// A non-service error occurred.
// A service error occurred.
fmt.Printf("Fatal: %v\n", err)
return err
}
}
return nil
}
//export FLBPluginRegister
func FLBPluginRegister(ctx unsafe.Pointer) int {
return output.FLBPluginRegister(ctx, "cloudwatch_logs", "ClooudwatchLogs Output plugin written in GO!")
}
//export FLBPluginInit
// (fluentbit will call this)
// ctx (context) pointer to fluentbit context (state/ c code)
func FLBPluginInit(ctx unsafe.Pointer) int {
// Example to retrieve an optional configuration parameter
credential := plugin.PluginConfigKey(ctx, "Credential")
accessKeyID := plugin.PluginConfigKey(ctx, "AccessKeyID")
secretAccessKey := plugin.PluginConfigKey(ctx, "SecretAccessKey")
logStreamName := plugin.PluginConfigKey(ctx, "LogGroupName")
logGroupName := plugin.PluginConfigKey(ctx, "LogStreamName")
region := plugin.PluginConfigKey(ctx, "Region")
autoCreateStream := plugin.PluginConfigKey(ctx, "AutoCreateStream")
config, err := getCloudWatchLogsConfig(accessKeyID, secretAccessKey, credential, logGroupName, logStreamName, region, autoCreateStream)
if err != nil {
plugin.Unregister(ctx)
plugin.Exit(1)
return output.FLB_ERROR
}
fmt.Printf("[flb-go] plugin credential parameter = '%s'\n", credential)
fmt.Printf("[flb-go] plugin accessKeyID parameter = '%s'\n", secretConfig(accessKeyID))
fmt.Printf("[flb-go] plugin secretAccessKey parameter = '%s'\n", secretConfig(secretAccessKey))
fmt.Printf("[flb-go] plugin logGroupName parameter = '%s'\n", logGroupName)
fmt.Printf("[flb-go] plugin logStreamName parameter = '%s'\n", logStreamName)
fmt.Printf("[flb-go] plugin region parameter = '%s'\n", region)
fmt.Printf("[flb-go] plugin autoCreateStream parameter = '%s'\n", autoCreateStream)
sess := session.New(&aws.Config{
Credentials: config.credentials,
Region: config.region,
})
cloudwatchLogs = cloudwatchlogs.New(sess)
configCtx = &cloudWatchLogsConf{
logGroupName: *config.logGroupName,
logStreamName: *config.logStreamName,
autoCreateStream: config.autoCreateStream,
}
if configCtx.autoCreateStream {
if !plugin.CheckLogGroupsExistence(configCtx.logGroupName) {
err := plugin.CreateLogGroup(configCtx.logGroupName)
if err != nil {
fmt.Printf("Failed to create logGroup. error: %v\n", err)
}
}
}
if configCtx.autoCreateStream {
if doesExist, nextToken := plugin.CheckLogStreamsExistence(configCtx.logGroupName, configCtx.logStreamName); doesExist {
sequenceTokensCtx = make(map[updateToken]string)
sequenceTokensCtx[updateToken{configCtx.logGroupName, configCtx.logStreamName}] = nextToken
} else {
err := plugin.CreateLogStream(configCtx.logGroupName, configCtx.logStreamName)
if err != nil {
fmt.Printf("Failed to create logStream. error: %v\n", err)
}
}
}
return output.FLB_OK
}
//export FLBPluginFlush
func FLBPluginFlush(data unsafe.Pointer, length C.int, tag *C.char) int {
var ret int
var ts interface{}
var record map[interface{}]interface{}
var events []*cloudwatchlogs.InputLogEvent
dec := plugin.NewDecoder(data, int(length))
for {
ret, ts, record = plugin.GetRecord(dec)
if ret != 0 {
break
}
// Get timestamp
var timestamp time.Time
switch t := ts.(type) {
case output.FLBTime:
timestamp = ts.(output.FLBTime).Time
case uint64:
timestamp = time.Unix(int64(t), 0)
default:
fmt.Print("timestamp isn't known format. Use current time.\n")
timestamp = time.Now()
}
line, err := createJSON(record)
if err != nil {
fmt.Printf("error creating message for CloudWatchLogs: %v\n", err)
continue
}
t := aws.TimeUnixMilli(timestamp)
events = append(events, &cloudwatchlogs.InputLogEvent{ // Mandatory
Message: aws.String(line), // Mandatory
Timestamp: aws.Int64(t), // Mandatory
})
}
resp, err := plugin.Put(events, sequenceTokensCtx[updateToken{configCtx.logGroupName, configCtx.logStreamName}])
if err != nil {
fmt.Printf("error sending message for CloudWatchLogs: %v\n", err)
if rejectedEvent := resp.RejectedLogEventsInfo; rejectedEvent != nil {
fmt.Printf("Rejected Event: %s\n", rejectedEvent.GoString())
}
return output.FLB_RETRY
}
sequenceTokensCtx[updateToken{configCtx.logGroupName, configCtx.logStreamName}] = nextSequenceToken(resp)
// Return options:
//
// output.FLB_OK = data have been processed.
// output.FLB_ERROR = unrecoverable error, do not try this again.
// output.FLB_RETRY = retry to flush later.
return output.FLB_OK
}
func secretConfig(parameter string) string {
if parameter != "" {
return "xxxxxx"
} else {
return ""
}
}
func nextSequenceToken(response *cloudwatchlogs.PutLogEventsOutput) string {
if response != nil {
return *response.NextSequenceToken
} else {
return ""
}
}
func createJSON(record map[interface{}]interface{}) (string, error) {
m := make(map[string]interface{})
for k, v := range record {
switch t := v.(type) {
case []byte:
// prevent encoding to base64
m[k.(string)] = string(t)
default:
m[k.(string)] = v
}
}
js, err := jsoniter.Marshal(m)
if err != nil {
return "{}", err
}
return string(js), nil
}
//export FLBPluginExit
func FLBPluginExit() int {
return output.FLB_OK
}
func main() {
}