-
Notifications
You must be signed in to change notification settings - Fork 263
Expand file tree
/
Copy pathtailersrc.go
More file actions
366 lines (325 loc) · 8.31 KB
/
Copy pathtailersrc.go
File metadata and controls
366 lines (325 loc) · 8.31 KB
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT
package logfile
import (
"bytes"
"log"
"os"
"sync"
"time"
"golang.org/x/text/encoding"
"github.com/aws/amazon-cloudwatch-agent/extension/entitystore"
"github.com/aws/amazon-cloudwatch-agent/internal/logscommon"
"github.com/aws/amazon-cloudwatch-agent/internal/state"
"github.com/aws/amazon-cloudwatch-agent/logs"
"github.com/aws/amazon-cloudwatch-agent/plugins/inputs/logfile/tail"
"github.com/aws/amazon-cloudwatch-agent/sdk/service/cloudwatchlogs"
)
const (
tailCloseThreshold = 3 * time.Second
)
var (
multilineWaitPeriod = 1 * time.Second
defaultBufferSize = 1
)
type LogEvent struct {
msg string
t time.Time
offset state.Range
src *tailerSrc
}
var _ logs.StatefulLogEvent = (*LogEvent)(nil)
func (le LogEvent) Message() string {
return le.msg
}
func (le LogEvent) Time() time.Time {
return le.t
}
func (le LogEvent) Done() {
le.RangeQueue().Enqueue(le.Range())
}
func (le LogEvent) Range() state.Range {
return le.offset
}
func (le LogEvent) RangeQueue() state.FileRangeQueue {
return le.src.stateManager
}
type tailerSrc struct {
group string
stream string
class string
fileGlobPath string
destination string
stateManager state.FileRangeManager
initialStateOffset int64
tailer *tail.Tail
autoRemoval bool
timestampFn func(string) (time.Time, string)
enc encoding.Encoding
maxEventSize int
retentionInDays int
outputFn func(logs.LogEvent)
isMLStart func(string) bool
filters []*LogFilter
done chan struct{}
startTailerOnce sync.Once
cleanUpFns []func()
backpressureFdDrop bool
buffer chan *LogEvent
stopOnce sync.Once
}
// Verify tailerSrc implements LogSrc
var _ logs.LogSrc = (*tailerSrc)(nil)
func NewTailerSrc(
group, stream, destination string,
stateManager state.FileRangeManager,
initialStateOffset int64,
logClass, fileGlobPath string,
tailer *tail.Tail,
autoRemoval bool,
isMultilineStartFn func(string) bool,
filters []*LogFilter,
timestampFn func(string) (time.Time, string),
enc encoding.Encoding,
maxEventSize int,
retentionInDays int,
backpressureMode logscommon.BackpressureMode,
) *tailerSrc {
ts := &tailerSrc{
group: group,
stream: stream,
destination: destination,
stateManager: stateManager,
initialStateOffset: initialStateOffset,
class: logClass,
fileGlobPath: fileGlobPath,
tailer: tailer,
autoRemoval: autoRemoval,
isMLStart: isMultilineStartFn,
filters: filters,
timestampFn: timestampFn,
enc: enc,
maxEventSize: maxEventSize,
retentionInDays: retentionInDays,
backpressureFdDrop: !autoRemoval && backpressureMode == logscommon.LogBackpressureModeFDRelease,
done: make(chan struct{}),
}
if ts.backpressureFdDrop {
ts.buffer = make(chan *LogEvent, defaultBufferSize)
}
go ts.stateManager.Run(state.Notification{
Delete: ts.tailer.FileDeletedCh,
Done: ts.done,
})
return ts
}
func (ts *tailerSrc) SetOutput(fn func(logs.LogEvent)) {
if fn == nil {
return
}
ts.outputFn = fn
ts.startTailerOnce.Do(func() {
go ts.runTail()
if ts.backpressureFdDrop {
go ts.runSender()
}
})
}
func (ts *tailerSrc) Group() string {
return ts.group
}
func (ts *tailerSrc) Stream() string {
return ts.stream
}
func (ts *tailerSrc) Description() string {
return ts.tailer.Filename
}
func (ts *tailerSrc) Destination() string {
return ts.destination
}
func (ts *tailerSrc) Retention() int {
return ts.retentionInDays
}
func (ts *tailerSrc) Class() string {
return ts.class
}
func (ts *tailerSrc) Stop() {
ts.stopOnce.Do(func() {
close(ts.done)
if ts.buffer != nil {
close(ts.buffer)
}
})
}
func (ts *tailerSrc) AddCleanUpFn(f func()) {
ts.cleanUpFns = append(ts.cleanUpFns, f)
}
func (ts *tailerSrc) Entity() *cloudwatchlogs.Entity {
es := entitystore.GetEntityStore()
if es != nil {
return es.CreateLogFileEntity(entitystore.LogFileGlob(ts.fileGlobPath), entitystore.LogGroupName(ts.group))
}
return nil
}
func (ts *tailerSrc) runTail() {
defer ts.cleanUp()
t := time.NewTicker(multilineWaitPeriod)
defer t.Stop()
var init string
var msgBuf bytes.Buffer
var cnt int
fo := state.Range{}
if ts.initialStateOffset > 0 {
fo.SetInt64(0, ts.initialStateOffset)
}
ignoreUntilNextEvent := false
for {
select {
// Warning: Make sure to release line once done!
case line, ok := <-ts.tailer.Lines:
if !ok {
ts.publishEvent(msgBuf, fo)
return
}
if line.Err != nil {
log.Printf("E! [logfile] Error tailing line in file %s, Error: %s\n", ts.tailer.Filename, line.Err)
ts.tailer.ReleaseLine(line)
continue
}
text := line.Text
if ts.enc != nil {
var err error
text, err = ts.enc.NewDecoder().String(text)
if err != nil {
log.Printf("E! [logfile] Cannot decode the log file content for %s: %v\n", ts.tailer.Filename, err)
ts.tailer.ReleaseLine(line)
continue
}
}
if ts.isMLStart == nil {
msgBuf.Reset()
msgBuf.WriteString(text)
fo.ShiftInt64(line.Offset)
init = ""
} else if ts.isMLStart(text) || (!ignoreUntilNextEvent && msgBuf.Len() == 0) {
init = text
ignoreUntilNextEvent = false
} else if ignoreUntilNextEvent || msgBuf.Len() >= ts.maxEventSize {
ignoreUntilNextEvent = true
fo.ShiftInt64(line.Offset)
ts.tailer.ReleaseLine(line)
continue
} else {
msgBuf.WriteString("\n")
msgBuf.WriteString(text)
fo.ShiftInt64(line.Offset)
ts.tailer.ReleaseLine(line)
continue
}
ts.publishEvent(msgBuf, fo)
msgBuf.Reset()
msgBuf.WriteString(init)
fo.ShiftInt64(line.Offset)
ts.tailer.ReleaseLine(line)
cnt = 0
case <-t.C:
if msgBuf.Len() > 0 {
cnt++
}
if cnt >= 5 {
ts.publishEvent(msgBuf, fo)
msgBuf.Reset()
cnt = 0
}
case <-ts.done:
return
}
}
}
func (ts *tailerSrc) publishEvent(msgBuf bytes.Buffer, fo state.Range) {
// helper to handle event publishing
if msgBuf.Len() == 0 {
return
}
msg := msgBuf.String()
timestamp, modifiedMsg := ts.timestampFn(msg)
e := &LogEvent{
msg: modifiedMsg,
t: timestamp,
offset: fo,
src: ts,
}
if ShouldPublish(ts.group, ts.stream, ts.filters, e) {
if ts.backpressureFdDrop {
select {
case ts.buffer <- e:
// successfully sent
case <-ts.done:
return
default:
// sender buffer is full. start timer to close file then retry
timer := time.NewTimer(tailCloseThreshold)
defer timer.Stop()
for {
select {
case ts.buffer <- e:
// sent event after buffer gets freed up
if ts.tailer.IsFileClosed() { // skip file closing if not already closed
if err := ts.tailer.Reopen(false); err != nil {
log.Printf("E! [logfile] error reopening file %s: %v", ts.tailer.Filename, err)
}
}
return
case <-timer.C:
// timer expired without successful send, close file
log.Printf("D! [logfile] tailer sender buffer blocked after retrying, closing file %v", ts.tailer.Filename)
ts.tailer.CloseFile()
case <-ts.done:
return
}
}
}
} else {
ts.outputFn(e)
}
}
}
func (ts *tailerSrc) runSender() {
log.Printf("D! [logfile] runSender starting for %s", ts.tailer.Filename)
for {
select {
case e, ok := <-ts.buffer:
if !ok { // buffer was closed
log.Printf("D! [logfile] runSender buffer was closed for %s", ts.tailer.Filename)
return
}
// Check done before sending
select {
case <-ts.done:
return
default:
if e != nil {
ts.outputFn(e)
}
}
case <-ts.done:
log.Printf("D! [logfile] runSender received done signal for %s", ts.tailer.Filename)
return
}
}
}
func (ts *tailerSrc) cleanUp() {
if ts.autoRemoval {
if err := os.Remove(ts.tailer.Filename); err != nil {
log.Printf("W! [logfile] Failed to auto remove file %v: %v", ts.tailer.Filename, err)
} else {
log.Printf("I! [logfile] Successfully removed file %v with auto_removal feature", ts.tailer.Filename)
}
}
for _, clf := range ts.cleanUpFns {
clf()
}
if ts.outputFn != nil {
ts.outputFn(nil) // inform logs agent the tailer src's exit, to stop runSrcToDest
}
}