-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
Copy pathfiletarget_test.go
651 lines (551 loc) · 18.2 KB
/
filetarget_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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
package file
import (
"bytes"
"context"
"fmt"
"math/rand"
"os"
"path/filepath"
"sort"
"sync"
"testing"
"time"
"github.com/fsnotify/fsnotify"
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/testutil"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/atomic"
"github.com/grafana/loki/v3/clients/pkg/promtail/client/fake"
"github.com/grafana/loki/v3/clients/pkg/promtail/positions"
)
func TestFileTargetSync(t *testing.T) {
w := log.NewSyncWriter(os.Stderr)
logger := log.NewLogfmtLogger(w)
dirName := newTestLogDirectories(t)
positionsFileName := filepath.Join(dirName, "positions.yml")
logDir1 := filepath.Join(dirName, "log1")
logDir1File1 := filepath.Join(logDir1, "test1.log")
logDir1File2 := filepath.Join(logDir1, "test2.log")
// Set the sync period to a really long value, to guarantee the sync timer never runs, this way we know
// everything saved was done through channel notifications when target.stop() was called.
ps, err := positions.New(logger, positions.Config{
SyncPeriod: 10 * time.Minute,
PositionsFile: positionsFileName,
})
if err != nil {
t.Fatal(err)
}
client := fake.New(func() {})
defer client.Stop()
metrics := NewMetrics(nil)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
fakeHandler := make(chan fileTargetEvent)
receivedStartWatch := atomic.NewInt32(0)
receivedStopWatch := atomic.NewInt32(0)
go func() {
for {
select {
case event := <-fakeHandler:
switch event.eventType {
case fileTargetEventWatchStart:
receivedStartWatch.Add(1)
case fileTargetEventWatchStop:
receivedStopWatch.Add(1)
}
case <-ctx.Done():
return
}
}
}()
path := logDir1 + "/*.log"
target, err := NewFileTarget(metrics, logger, client, ps, path, "", nil, nil, &Config{
SyncPeriod: 1 * time.Minute, // assure the sync is not called by the ticker
}, DefaultWatchConig, nil, fakeHandler, "", nil)
assert.NoError(t, err)
target.mu.Lock()
// Start with nothing watched.
if len(target.watches) != 0 {
t.Fatal("Expected watches to be 0 at this point in the test...")
}
if len(target.readers) != 0 {
t.Fatal("Expected tails to be 0 at this point in the test...")
}
target.mu.Unlock()
// Create the base dir, still nothing watched.
err = os.MkdirAll(logDir1, 0750)
assert.NoError(t, err)
err = target.sync()
assert.NoError(t, err)
target.mu.Lock()
if len(target.watches) != 0 {
t.Fatal("Expected watches to be 0 at this point in the test...")
}
if len(target.readers) != 0 {
t.Fatal("Expected tails to be 0 at this point in the test...")
}
target.mu.Unlock()
// Add a file, which should create a watcher and a tailer.
_, err = os.Create(logDir1File1)
assert.NoError(t, err)
// Delay sync() call to make sure the filesystem watch event does not fire during sync()
time.Sleep(10 * time.Millisecond)
err = target.sync()
assert.NoError(t, err)
assert.Equal(t, 1, len(target.watches),
"Expected watches to be 1 at this point in the test...",
)
assert.Equal(t, 1, len(target.readers),
"Expected tails to be 1 at this point in the test...",
)
requireEventually(t, func() bool {
return receivedStartWatch.Load() == 1
}, "Expected received starting watch event to be 1 at this point in the test...")
// Add another file, should get another tailer.
_, err = os.Create(logDir1File2)
assert.NoError(t, err)
err = target.sync()
assert.NoError(t, err)
assert.Equal(t, 1, len(target.watches),
"Expected watches to be 1 at this point in the test...",
)
assert.Equal(t, 2, len(target.readers),
"Expected tails to be 2 at this point in the test...",
)
// Remove one of the files, tailer should stop.
err = os.Remove(logDir1File1)
assert.NoError(t, err)
err = target.sync()
assert.NoError(t, err)
target.mu.Lock()
assert.Equal(t, 1, len(target.watches),
"Expected watches to be 1 at this point in the test...",
)
assert.Equal(t, 1, len(target.readers),
"Expected tails to be 1 at this point in the test...",
)
target.mu.Unlock()
// Remove the entire directory, other tailer should stop and watcher should go away.
err = os.RemoveAll(logDir1)
assert.NoError(t, err)
err = target.sync()
assert.NoError(t, err)
target.mu.Lock()
assert.Equal(t, 0, len(target.watches),
"Expected watches to be 0 at this point in the test...",
)
assert.Equal(t, 0, len(target.readers),
"Expected tails to be 0 at this point in the test...",
)
target.mu.Unlock()
requireEventually(t, func() bool {
return receivedStartWatch.Load() == 1
}, "Expected received starting watch event to be 1 at this point in the test...")
requireEventually(t, func() bool {
return receivedStartWatch.Load() == 1
}, "Expected received stopping watch event to be 1 at this point in the test...")
target.Stop()
ps.Stop()
}
func TestFileTarget_StopsTailersCleanly(t *testing.T) {
w := log.NewSyncWriter(os.Stderr)
logger := log.NewLogfmtLogger(w)
tempDir := t.TempDir()
positionsFileName := filepath.Join(tempDir, "positions.yml")
logFile := filepath.Join(tempDir, "test1.log")
ps, err := positions.New(logger, positions.Config{
SyncPeriod: 10 * time.Millisecond,
PositionsFile: positionsFileName,
})
require.NoError(t, err)
client := fake.New(func() {})
defer client.Stop()
fakeHandler := make(chan fileTargetEvent, 10)
pathToWatch := filepath.Join(tempDir, "*.log")
registry := prometheus.NewRegistry()
target, err := NewFileTarget(NewMetrics(registry), logger, client, ps, pathToWatch, "", nil, nil, &Config{
SyncPeriod: 10 * time.Millisecond,
}, DefaultWatchConig, nil, fakeHandler, "", nil)
assert.NoError(t, err)
_, err = os.Create(logFile)
assert.NoError(t, err)
requireEventually(t, func() bool {
target.mu.Lock()
defer target.mu.Unlock()
return len(target.readers) == 1
}, "expected 1 tailer to be created")
require.NoError(t, testutil.GatherAndCompare(registry, bytes.NewBufferString(`
# HELP promtail_files_active_total Number of active files.
# TYPE promtail_files_active_total gauge
promtail_files_active_total 1
`), "promtail_files_active_total"))
// Inject an error to tailer
initailTailer := target.readers[logFile].(*tailer)
_ = initailTailer.tail.Tomb.Killf("test: network file systems can be unreliable")
// Tailer will be replaced by a new one
requireEventually(t, func() bool {
target.mu.Lock()
defer target.mu.Unlock()
return len(target.readers) == 1 && target.readers[logFile].(*tailer) != initailTailer
}, "expected dead tailer to be replaced by a new one")
// The old tailer should be stopped:
select {
case <-initailTailer.done:
case <-time.After(time.Second * 10):
t.Fatal("expected position timer to be stopped cleanly")
}
// The old tailer's position timer should be stopped
select {
case <-initailTailer.posdone:
case <-time.After(time.Second * 10):
t.Fatal("expected position timer to be stopped cleanly")
}
target.Stop()
ps.Stop()
require.NoError(t, testutil.GatherAndCompare(registry, bytes.NewBufferString(`
# HELP promtail_files_active_total Number of active files.
# TYPE promtail_files_active_total gauge
promtail_files_active_total 0
`), "promtail_files_active_total"))
}
func TestFileTarget_StopsTailersCleanly_Parallel(t *testing.T) {
w := log.NewSyncWriter(os.Stderr)
logger := log.NewLogfmtLogger(w)
tempDir := t.TempDir()
positionsFileName := filepath.Join(tempDir, "positions.yml")
ps, err := positions.New(logger, positions.Config{
SyncPeriod: 10 * time.Millisecond,
PositionsFile: positionsFileName,
})
require.NoError(t, err)
client := fake.New(func() {})
defer client.Stop()
pathToWatch := filepath.Join(tempDir, "*.log")
registry := prometheus.NewRegistry()
metrics := NewMetrics(registry)
// Increase this to several thousand to make the test more likely to fail when debugging a race condition
iterations := 500
fakeHandler := make(chan fileTargetEvent, 10*iterations)
for i := 0; i < iterations; i++ {
logFile := filepath.Join(tempDir, fmt.Sprintf("test_%d.log", i))
target, err := NewFileTarget(metrics, logger, client, ps, pathToWatch, "", nil, nil, &Config{
SyncPeriod: 10 * time.Millisecond,
}, DefaultWatchConig, nil, fakeHandler, "", nil)
assert.NoError(t, err)
file, err := os.Create(logFile)
assert.NoError(t, err)
// Write some data to the file
for j := 0; j < 5; j++ {
_, _ = file.WriteString(fmt.Sprintf("test %d\n", j))
}
require.NoError(t, file.Close())
requireEventually(t, func() bool {
return testutil.CollectAndCount(registry, "promtail_read_lines_total") == 1
}, "expected 1 read_lines_total metric")
requireEventually(t, func() bool {
return testutil.CollectAndCount(registry, "promtail_read_bytes_total") == 1
}, "expected 1 read_bytes_total metric")
requireEventually(t, func() bool {
return testutil.ToFloat64(metrics.readLines) == 5
}, "expected 5 read_lines_total")
requireEventually(t, func() bool {
return testutil.ToFloat64(metrics.totalBytes) == 35
}, "expected 35 total_bytes")
requireEventually(t, func() bool {
return testutil.ToFloat64(metrics.readBytes) == 35
}, "expected 35 read_bytes")
// Concurrently stop the target and remove the file
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
sleepRandomDuration(time.Millisecond * 10)
target.Stop()
wg.Done()
}()
go func() {
sleepRandomDuration(time.Millisecond * 10)
_ = os.Remove(logFile)
wg.Done()
}()
wg.Wait()
requireEventually(t, func() bool {
return testutil.CollectAndCount(registry, "promtail_read_bytes_total") == 0
}, "expected read_bytes_total metric to be cleaned up")
requireEventually(t, func() bool {
return testutil.CollectAndCount(registry, "promtail_file_bytes_total") == 0
}, "expected file_bytes_total metric to be cleaned up")
}
ps.Stop()
}
func TestFileTargetPathExclusion(t *testing.T) {
w := log.NewSyncWriter(os.Stderr)
logger := log.NewLogfmtLogger(w)
dirName := newTestLogDirectories(t)
positionsFileName := filepath.Join(dirName, "positions.yml")
logDir1 := filepath.Join(dirName, "log1")
logDir2 := filepath.Join(dirName, "log2")
logDir3 := filepath.Join(dirName, "log3")
logFiles := []string{
filepath.Join(logDir1, "test1.log"),
filepath.Join(logDir1, "test2.log"),
filepath.Join(logDir2, "test1.log"),
filepath.Join(logDir3, "test1.log"),
filepath.Join(logDir3, "test2.log"),
}
// Set the sync period to a really long value, to guarantee the sync timer never runs, this way we know
// everything saved was done through channel notifications when target.stop() was called.
ps, err := positions.New(logger, positions.Config{
SyncPeriod: 10 * time.Minute,
PositionsFile: positionsFileName,
})
if err != nil {
t.Fatal(err)
}
client := fake.New(func() {})
defer client.Stop()
metrics := NewMetrics(nil)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
fakeHandler := make(chan fileTargetEvent)
receivedStartWatch := atomic.NewInt32(0)
receivedStopWatch := atomic.NewInt32(0)
go func() {
for {
select {
case event := <-fakeHandler:
switch event.eventType {
case fileTargetEventWatchStart:
receivedStartWatch.Add(1)
case fileTargetEventWatchStop:
receivedStopWatch.Add(1)
}
case <-ctx.Done():
return
}
}
}()
path := filepath.Join(dirName, "**", "*.log")
pathExclude := filepath.Join(dirName, "log3", "*.log")
target, err := NewFileTarget(metrics, logger, client, ps, path, pathExclude, nil, nil, &Config{
SyncPeriod: 1 * time.Minute, // assure the sync is not called by the ticker
}, DefaultWatchConig, nil, fakeHandler, "", nil)
assert.NoError(t, err)
// Start with nothing watched.
target.mu.Lock()
if len(target.watches) != 0 {
t.Fatal("Expected watches to be 0 at this point in the test...")
}
target.mu.Unlock()
if len(target.readers) != 0 {
t.Fatal("Expected tails to be 0 at this point in the test...")
}
// Create the base directories, still nothing watched.
err = os.MkdirAll(logDir1, 0750)
assert.NoError(t, err)
err = os.MkdirAll(logDir2, 0750)
assert.NoError(t, err)
err = os.MkdirAll(logDir3, 0750)
assert.NoError(t, err)
err = target.sync()
assert.NoError(t, err)
if len(target.watches) != 0 {
t.Fatal("Expected watches to be 0 at this point in the test...")
}
if len(target.readers) != 0 {
t.Fatal("Expected tails to be 0 at this point in the test...")
}
// Create all the files, which should create two directory watchers and three file tailers.
for _, f := range logFiles {
_, err = os.Create(f)
assert.NoError(t, err)
}
// Delay sync() call to make sure the filesystem watch event does not fire during sync()
time.Sleep(10 * time.Millisecond)
err = target.sync()
assert.NoError(t, err)
assert.Equal(t, 2, len(target.watches),
"Expected watches to be 2 at this point in the test...",
)
assert.Equal(t, 3, len(target.readers),
"Expected tails to be 3 at this point in the test...",
)
requireEventually(t, func() bool {
return receivedStartWatch.Load() == 2
}, "Expected received starting watch event to be 2 at this point in the test...")
requireEventually(t, func() bool {
return receivedStopWatch.Load() == 0
}, "Expected received stopping watch event to be 0 at this point in the test...")
// Remove the first directory, other tailer should stop and its watchers should go away.
// Only the non-excluded `logDir2` should be watched.
err = os.RemoveAll(logDir1)
assert.NoError(t, err)
err = target.sync()
assert.NoError(t, err)
assert.Equal(t, 1, len(target.watches),
"Expected watches to be 1 at this point in the test...",
)
assert.Equal(t, 1, len(target.readers),
"Expected tails to be 1 at this point in the test...",
)
requireEventually(t, func() bool {
return receivedStartWatch.Load() == 2
}, "Expected received starting watch event to still be 2 at this point in the test...")
requireEventually(t, func() bool {
return receivedStopWatch.Load() == 1
}, "Expected received stopping watch event to be 1 at this point in the test...")
require.NoError(t, os.RemoveAll(logDir2))
require.NoError(t, os.RemoveAll(logDir3))
require.NoError(t, target.sync())
target.Stop()
ps.Stop()
}
func TestHandleFileCreationEvent(t *testing.T) {
w := log.NewSyncWriter(os.Stderr)
logger := log.NewLogfmtLogger(w)
dirName := newTestLogDirectories(t)
positionsFileName := filepath.Join(dirName, "positions.yml")
logDir := filepath.Join(dirName, "log")
logFile := filepath.Join(logDir, "test1.log")
logFileIgnored := filepath.Join(logDir, "test.donot.log")
if err := os.MkdirAll(logDir, 0750); err != nil {
t.Fatal(err)
}
// Set the sync period to a really long value, to guarantee the sync timer never runs, this way we know
// everything saved was done through channel notifications when target.stop() was called.
ps, err := positions.New(logger, positions.Config{
SyncPeriod: 10 * time.Minute,
PositionsFile: positionsFileName,
})
if err != nil {
t.Fatal(err)
}
client := fake.New(func() {})
defer client.Stop()
metrics := NewMetrics(nil)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
fakeFileHandler := make(chan fsnotify.Event)
fakeTargetHandler := make(chan fileTargetEvent)
path := logDir + "/*.log"
go func() {
for {
select {
case <-fakeTargetHandler:
continue
case <-ctx.Done():
return
}
}
}()
pathExclude := "**/*.donot.log"
target, err := NewFileTarget(metrics, logger, client, ps, path, pathExclude, nil, nil, &Config{
// To handle file creation event from channel, set enough long time as sync period
SyncPeriod: 10 * time.Minute,
}, DefaultWatchConig, fakeFileHandler, fakeTargetHandler, "", nil)
if err != nil {
t.Fatal(err)
}
_, err = os.Create(logFile)
if err != nil {
t.Fatal(err)
}
_, err = os.Create(logFileIgnored)
if err != nil {
t.Fatal(err)
}
fakeFileHandler <- fsnotify.Event{
Name: logFile,
Op: fsnotify.Create,
}
fakeFileHandler <- fsnotify.Event{
Name: logFileIgnored,
Op: fsnotify.Create,
}
requireEventually(t, func() bool {
return len(target.readers) == 1
}, "Expected tails to be 1 at this point in the test...")
}
func TestToStopTailing(t *testing.T) {
nt := []string{"file1", "file2", "file3", "file4", "file5", "file6", "file7", "file11", "file12", "file15"}
et := make(map[string]Reader, 15)
for i := 1; i <= 15; i++ {
et[fmt.Sprintf("file%d", i)] = nil
}
st := toStopTailing(nt, et)
sort.Strings(st)
expected := []string{"file10", "file13", "file14", "file8", "file9"}
if len(st) != len(expected) {
t.Error("Expected 5 tailers to be stopped, got", len(st))
}
for i := range expected {
if st[i] != expected[i] {
t.Error("Results mismatch, expected", expected[i], "got", st[i])
}
}
}
func BenchmarkToStopTailing(b *testing.B) {
nt := []string{"file1", "file2", "file3", "file4", "file5", "file6", "file7", "file11", "file12", "file15"}
et := make(map[string]Reader, 15)
for i := 1; i <= 15; i++ {
et[fmt.Sprintf("file%d", i)] = nil
}
for n := 0; n < b.N; n++ {
toStopTailing(nt, et)
}
}
func TestMissing(t *testing.T) {
a := map[string]struct{}{}
b := map[string]struct{}{}
c := missing(a, b)
if len(c) != 0 {
t.Error("Expected no results with empty sets")
}
a["str1"] = struct{}{}
a["str2"] = struct{}{}
a["str3"] = struct{}{}
c = missing(a, b)
if len(c) != 0 {
t.Error("Expected no results with empty b set")
}
c = missing(b, a)
if len(c) != 3 {
t.Error("Expected three results")
}
if _, ok := c["str1"]; !ok {
t.Error("Expected the set to contain str1 but it did not")
}
if _, ok := c["str2"]; !ok {
t.Error("Expected the set to contain str2 but it did not")
}
if _, ok := c["str3"]; !ok {
t.Error("Expected the set to contain str3 but it did not")
}
b["str1"] = struct{}{}
b["str4"] = struct{}{}
c = missing(a, b)
if len(c) != 1 {
t.Error("Expected one result")
}
if _, ok := c["str4"]; !ok {
t.Error("Expected the set to contain str4 but it did not")
}
c = missing(b, a)
if len(c) != 2 {
t.Error("Expected two results")
}
if _, ok := c["str2"]; !ok {
t.Error("Expected the set to contain str2 but it did not")
}
if _, ok := c["str3"]; !ok {
t.Error("Expected the set to contain str3 but it did not")
}
}
func requireEventually(t *testing.T, f func() bool, msg string) {
t.Helper()
require.Eventually(t, f, time.Second*10, time.Millisecond, msg)
}
func sleepRandomDuration(maxDuration time.Duration) {
time.Sleep(time.Duration(rand.Int63n(int64(maxDuration))))
}