-
Notifications
You must be signed in to change notification settings - Fork 0
/
log_watcher_test.go
359 lines (323 loc) · 7.78 KB
/
log_watcher_test.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
package llogtail
import (
"fmt"
"math/rand"
"os"
"os/exec"
"testing"
"time"
"github.com/eapache/queue"
)
var kWatcherCloseC chan struct{}
const kPoller = 3 * time.Second
var kLogs = []string{
"tests/error.log", "tests/info.log", "tests/warn.log",
}
type kSimEvent struct {
path string
// inode int
e LogFileEvent
}
type EventReceiver struct {
eventQ map[string]*queue.Queue
closeC chan struct{}
eventC chan *Event
}
func NewEventReceiver(eventC chan *Event) *EventReceiver {
return &EventReceiver{
eventQ: make(map[string]*queue.Queue),
closeC: make(chan struct{}),
eventC: eventC,
}
}
func (er *EventReceiver) Run() {
logger.Notice("Receive Backgroud Task Start")
go func() {
for {
select {
case e := <-er.eventC:
logger.Info("ReceiveQ <= ", e.String())
if _, ok := er.eventQ[e.meta.path]; !ok {
er.eventQ[e.meta.path] = queue.New()
}
er.eventQ[e.meta.path].Add(e)
case <-er.closeC:
logger.Notice("Receive Backgroud Task Exit")
return
}
}
}()
}
func (er *EventReceiver) Draining() {
for _, v := range er.eventQ {
for v.Length() != 0 {
v.Remove()
}
}
}
func (er *EventReceiver) Match(events []kSimEvent) error {
for _, kEvent := range events {
q, ok := er.eventQ[kEvent.path]
if !ok {
return fmt.Errorf("Path %v not found in Receiver", kEvent.path)
}
if q.Length() <= 0 {
return fmt.Errorf("EventQ %v Empty, expect %v", kEvent.path, kEvent.e)
}
event, _ := q.Remove().(*Event)
if event.e != kEvent.e {
return fmt.Errorf("%v, expect %v, actual %v", kEvent.path, kEvent, event.e)
}
}
return nil
}
func (er *EventReceiver) Stop() {
er.closeC <- struct{}{}
}
func Pre() {
InitLogger(&defauleLogOption)
shell := `rm -rf tests offset && mkdir -p tests offset && cd tests && touch error.log warn.log info.log collector.json sink.json && echo '{
"dir": "./tests",
"pattern": "*.log",
"lineSeperator": "\\n",
"sink": {
"type": "file",
"config": "tests/sink.json"
},
"watcher": {
"filter": 1,
"poller": 3
}
}' > collector.json && echo '{ "dst": "./tests/dst.txt" }' > sink.json`
_, err := exec.Command("sh", "-c", shell).Output()
if err != nil {
logger.Errorf("shell %v", shell)
panic("Pre -> " + err.Error())
}
logger.Notice("Pre Success")
}
func TestLogWatcher(t *testing.T) {
Pre()
dir, pattern := "tests", "*.log"
var receiver *EventReceiver
watcher := NewLogWatcher(
&LogWatchOption{
FilterInterval: time.Microsecond * 300,
PollerInterval: kPoller,
},
)
t.Run("Test Watcher Init", func(t *testing.T) {
if err := watcher.Init(); err != nil {
logger.Errorf("Watcher Init -> %w", err)
t.FailNow()
}
})
receiver = NewEventReceiver(watcher.EventC)
receiver.Run()
watcher.RunEventHandler()
defer receiver.Stop()
defer watcher.Close()
t.Run("Test Watcher RegisterAndWatch", func(t *testing.T) {
defer receiver.Draining()
if err := watcher.RegisterAndWatch(dir, pattern); err != nil {
logger.Errorf("Watcher RegisterAndWatch -> %w", err)
t.FailNow()
}
time.Sleep(time.Microsecond * 200)
expected := []kSimEvent{
{
"tests/error.log", LogFileDiscover,
}, {
"tests/info.log", LogFileDiscover,
}, {
"tests/warn.log", LogFileDiscover,
},
}
if err := receiver.Match(expected); err != nil {
logger.Error("Event not Match", err)
t.FailNow()
}
})
t.Run("Test Watch Modify Event", func(t *testing.T) {
defer receiver.Draining()
for _, logf := range kLogs {
modify(logf, kDataOneKB)
}
time.Sleep(time.Millisecond * 100)
if err := receiver.Match([]kSimEvent{
{
"tests/error.log", LogFileModify,
}, {
"tests/info.log", LogFileModify,
}, {
"tests/warn.log", LogFileModify,
},
}); err != nil {
logger.Error("Event not Match", err)
t.FailNow()
}
})
t.Run("Test Watch Rename Rorate Event", func(t *testing.T) {
defer receiver.Draining()
for _, logf := range kLogs {
// modify(logf,kDataOneKB)
rotate(logf)
}
time.Sleep(time.Millisecond * 100)
if err := receiver.Match([]kSimEvent{
{
"tests/error.log", LogFileRenameRotate,
}, {
"tests/info.log", LogFileRenameRotate,
}, {
"tests/warn.log", LogFileRenameRotate,
},
}); err != nil {
logger.Error("Event not Match", err)
t.FailNow()
}
})
t.Run("Test Watch Modify After Rename Rorate Event", func(t *testing.T) {
defer receiver.Draining()
for _, logf := range kLogs {
modify(logf, kDataOneKB)
}
time.Sleep(time.Millisecond * 100)
if err := receiver.Match([]kSimEvent{
{
"tests/error.log", LogFileModify,
}, {
"tests/info.log", LogFileModify,
}, {
"tests/warn.log", LogFileModify,
},
}); err != nil {
logger.Error("Event not Match", err)
t.FailNow()
}
})
t.Run("Test Watch Remove Event", func(t *testing.T) {
defer receiver.Draining()
for _, logf := range kLogs {
remove(logf)
}
time.Sleep(time.Millisecond * 100)
if err := receiver.Match([]kSimEvent{
{
"tests/error.log", LogFileRemove,
}, {
"tests/info.log", LogFileRemove,
}, {
"tests/warn.log", LogFileRemove,
},
}); err != nil {
logger.Error("Event not Match", err)
t.FailNow()
}
})
t.Run("Test Watcher Poller", func(t *testing.T) {
defer receiver.Draining()
Pre()
receiver.Draining()
logger.Notice("Sleep for Poller")
time.Sleep(kPoller + time.Second)
if err := receiver.Match([]kSimEvent{
{
"tests/error.log", LogFileRenameRotate,
}, {
"tests/info.log", LogFileRenameRotate,
}, {
"tests/warn.log", LogFileRenameRotate,
},
}); err != nil {
logger.Error("Event not Match", err)
t.FailNow()
}
})
t.Run("Test Watcher Lazy Logger", func(t *testing.T) {
defer receiver.Draining()
Pre()
receiver.Draining()
os.Create("./tests/tt.log")
logger.Notice("Sleep for Poller")
time.Sleep(kPoller + time.Second)
if err := receiver.Match([]kSimEvent{
{
"tests/error.log", LogFileRenameRotate,
}, {
"tests/info.log", LogFileRenameRotate,
}, {
"tests/warn.log", LogFileRenameRotate,
},
{
"tests/tt.log", LogFileDiscover,
},
}); err != nil {
logger.Error("Event not Match", err)
t.FailNow()
}
})
}
var kDataOneKB = generateDataOneKB()
// generateDataOneKB generates 1KB of random data
func generateDataOneKB() []byte {
rand.NewSource(time.Now().UnixNano())
data := make([]byte, 1023) // 1KB = 1024 Bytes
ch := byte('a' + rand.Intn(26))
for i := range data {
data[i] = ch // Random byte value between 0-255
}
data = append(data, '\n')
return data
}
// modify 文件内容修改函数
func modify(path string, newData []byte) {
if err := os.WriteFile(path, newData, 0644); err != nil {
logger.Errorf("modify %v", path)
panic(err)
}
}
func appendf(path string, newData []byte) {
// Open the file in append mode (os.O_APPEND) and write-only mode (os.O_WRONLY)
file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0644)
if err != nil {
logger.Error("Error:", err)
panic(err)
}
defer file.Close()
// Write the new data to the file
_, err = file.Write(newData)
if err != nil {
logger.Error("Error:", err)
panic(err)
}
}
func rename(oldPath, newPath string) {
if err := os.Rename(oldPath, newPath); err != nil {
logger.Errorf("rename %v -> %v", oldPath, newPath)
panic(err)
}
}
func remove(path string) {
if err := os.Remove(path); err != nil {
logger.Errorf("remove %v -> %v", path)
panic(err)
}
}
// rotateLogs 对指定的日志文件进行轮转
func rotate(logPath string) error {
currentTime := time.Now()
newLogName := fmt.Sprintf("%s.%d-%02d-%02dT%02d-%02d-%02d-%v",
logPath, currentTime.Year(), currentTime.Month(), currentTime.Day(),
currentTime.Hour(), currentTime.Minute(), currentTime.Second(), currentTime.UnixNano())
err := os.Rename(logPath, newLogName)
if err != nil {
return err
}
newFile, err := os.Create(logPath)
if err != nil {
return err
}
newFile.Close()
return nil
}