forked from lestrrat-go/fluent-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fluent_test.go
748 lines (657 loc) · 17.5 KB
/
fluent_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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
package fluent_test
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"path/filepath"
"strconv"
"sync"
"testing"
"time"
fluent "github.com/lestrrat-go/fluent-client"
msgpack "github.com/lestrrat-go/msgpack"
pdebug "github.com/lestrrat-go/pdebug"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
)
// to hell with race-conditions. no locking!
type server struct {
cleanup func()
done chan struct{}
listener net.Listener
mu sync.RWMutex
ready chan struct{}
useJSON bool
Network string
Address string
payload []*fluent.Message
}
func newServer(useJSON bool) (*server, error) {
dir, err := ioutil.TempDir("", "sock-")
if err != nil {
return nil, errors.Wrap(err, `failed to create temporary directory`)
}
file := filepath.Join(dir, "test-server.sock")
l, err := net.Listen("unix", file)
if err != nil {
return nil, errors.Wrap(err, `failed to listen to unix socket`)
}
s := &server{
Network: "unix",
Address: file,
useJSON: useJSON,
done: make(chan struct{}),
ready: make(chan struct{}),
listener: l,
cleanup: func() {
l.Close()
os.RemoveAll(dir)
},
}
return s, nil
}
func (s *server) Close() error {
if f := s.cleanup; f != nil {
f()
}
return nil
}
func (s *server) Ready() <-chan struct{} {
return s.ready
}
func (s *server) Done() <-chan struct{} {
return s.done
}
func (s *server) PayloadAt(i int) *fluent.Message {
s.mu.RLock()
m := s.payload[i]
s.mu.RUnlock()
return m
}
func (s *server) PayloadCount() int {
s.mu.RLock()
c := len(s.payload)
s.mu.RUnlock()
return c
}
func (s *server) PayloadIter() <-chan *fluent.Message {
s.mu.RLock()
ch := make(chan *fluent.Message, len(s.payload))
for _, p := range s.payload {
ch <- p
}
s.mu.RUnlock()
close(ch)
return ch
}
func (s *server) TruncatePayload() {
s.mu.Lock()
s.payload = s.payload[:0]
s.mu.Unlock()
}
func (s *server) AddPayload(v *fluent.Message) {
s.mu.Lock()
s.payload = append(s.payload, v)
s.mu.Unlock()
}
func (s *server) Run(ctx context.Context) {
if pdebug.Enabled {
defer pdebug.Printf("bail out of server.Run")
}
defer close(s.done)
go func() {
<-ctx.Done()
if pdebug.Enabled {
pdebug.Printf("context.Context is done, closing listeners")
}
s.listener.Close()
}()
if pdebug.Enabled {
pdebug.Printf("server started")
}
var once sync.Once
for {
if pdebug.Enabled {
pdebug.Printf("server loop")
}
select {
case <-ctx.Done():
if pdebug.Enabled {
pdebug.Printf("cancel detected in server.Run")
}
return
default:
}
readerCh := make(chan *fluent.Message)
go func(ch chan *fluent.Message) {
if pdebug.Enabled {
defer pdebug.Printf("bailing out of server reader")
}
ACCEPT:
for {
select {
case <-ctx.Done():
return
default:
}
once.Do(func() { close(s.ready) })
conn, err := s.listener.Accept()
if err != nil {
if pdebug.Enabled {
pdebug.Printf("Failed to accept: %s", err)
}
return
}
if pdebug.Enabled {
pdebug.Printf("Accepted new connection")
}
var dec func(interface{}) error
if s.useJSON {
dec = json.NewDecoder(conn).Decode
} else {
dec = msgpack.NewDecoder(conn).Decode
}
for {
if pdebug.Enabled {
pdebug.Printf("waiting for next message...")
}
// conn.SetReadDeadline(time.Now().Add(5 * time.Second))
var v fluent.Message
if err := dec(&v); err != nil {
var decName string
if s.useJSON {
decName = "json"
} else {
decName = "msgpack"
}
if pdebug.Enabled {
pdebug.Printf("test server: failed to decode %s: %s", decName, err)
}
if errors.Cause(err) == io.EOF {
if pdebug.Enabled {
pdebug.Printf("test server: EOF detected")
}
conn.Close()
continue ACCEPT
}
continue
}
if pdebug.Enabled {
pdebug.Printf("Read new fluet.Message")
}
select {
case <-ctx.Done():
if pdebug.Enabled {
pdebug.Printf("bailing out of read loop")
}
return
case ch <- &v:
if pdebug.Enabled {
pdebug.Printf("Sent new message to read channel")
}
}
}
}
}(readerCh)
for {
var v *fluent.Message
select {
case <-ctx.Done():
if pdebug.Enabled {
pdebug.Printf("bailout")
}
return
case v = <-readerCh:
if pdebug.Enabled {
pdebug.Printf("new payload: %#v", v)
}
}
// This is some silly stuff, but msgpack would return
// us map[interface{}]interface{} instead of map[string]interface{}
// we force the usage of map[string]interface here, so testing is easier
switch v.Record.(type) {
case map[interface{}]interface{}:
newMap := map[string]interface{}{}
for key, val := range v.Record.(map[interface{}]interface{}) {
newMap[key.(string)] = val
}
v.Record = newMap
}
s.AddPayload(v)
}
}
}
func TestConnectOnStart(t *testing.T) {
for _, buffered := range []bool{true, false} {
buffered := buffered
t.Run(fmt.Sprintf("failure case, buffered=%t", buffered), func(t *testing.T) {
// find a port that is not available (this may be timing dependent)
var dialer net.Dialer
var port int = 22412
for i := 0; i < 1000; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
conn, err := dialer.DialContext(ctx, `net`, fmt.Sprintf(`127.0.0.1:%d`, port))
cancel()
if err == nil {
port++
conn.Close()
continue
}
break
}
client, err := fluent.New(
fluent.WithAddress(fmt.Sprintf(`127.0.0.1:%d`, port)),
fluent.WithConnectOnStart(true),
fluent.WithBuffered(buffered),
)
if !assert.Error(t, err, `fluent.New should fail`) {
client.Close()
return
}
})
}
s, err := newServer(false)
if !assert.NoError(t, err, "newServer should succeed") {
return
}
defer s.Close()
// This is just to stop the server
sctx, scancel := context.WithCancel(context.Background())
defer scancel()
go s.Run(sctx)
<-s.Ready()
for _, buffered := range []bool{true, false} {
buffered := buffered
t.Run(fmt.Sprintf("normal case, buffered=%t", buffered), func(t *testing.T) {
client, err := fluent.New(
fluent.WithNetwork(s.Network),
fluent.WithAddress(s.Address),
fluent.WithConnectOnStart(true),
fluent.WithBuffered(buffered),
)
if !assert.NoError(t, err, "fluent.New should succeed") {
return
}
client.Close()
})
}
}
func TestCloseAndPost(t *testing.T) {
client, err := fluent.New()
if !assert.NoError(t, err, `fluent.New should succeed`) {
return
}
// immediately close
client.Close()
if !assert.Error(t, client.Post("tag_name", nil), `we should error after a call to Close()`) {
return
}
}
func TestWithContext(t *testing.T) {
client, err := fluent.New()
if !assert.NoError(t, err, `fluent.New should succeed`) {
return
}
ctx, cancel := context.WithCancel(context.Background())
cancel() // cancel early
// Make sure ctx is closed
<-ctx.Done()
if !assert.Error(t, client.Post("tag_name", "Hello, World", fluent.WithContext(ctx)), `we should error after context is canceled`) {
return
}
}
func TestTagPrefix(t *testing.T) {
s, err := newServer(false)
if !assert.NoError(t, err, "newServer should succeed") {
return
}
defer s.Close()
// This is just to stop the server
sctx, scancel := context.WithCancel(context.Background())
defer scancel()
go s.Run(sctx)
<-s.Ready()
client, _ := fluent.New(
fluent.WithNetwork(s.Network),
fluent.WithAddress(s.Address),
fluent.WithTagPrefix("test"),
)
if !assert.NoError(t, client.Post("tag_name", map[string]interface{}{"foo": 1}), "Post should succeed") {
return
}
client.Shutdown(context.TODO())
for p := range s.PayloadIter() {
if !assert.Equal(t, "test.tag_name", p.Tag, "tag should have prefix") {
return
}
}
}
func TestBufferFull(t *testing.T) {
s, err := newServer(false)
if !assert.NoError(t, err, "newServer should succeed") {
return
}
defer s.Close()
client, _ := fluent.New(
fluent.WithNetwork(s.Network),
fluent.WithAddress(s.Address),
fluent.WithBufferLimit(256),
fluent.WithWriteThreshold(1),
)
count := 1
// Write until buffer is full.
if !assert.NoError(t, client.Post("tag_name", map[string]interface{}{"foo": 0}, fluent.WithSyncAppend(true)), "Post should succeed") {
return
}
for i := 1; ; i++ {
err := client.Post("tag_name", map[string]interface{}{"foo": i}, fluent.WithSyncAppend(true))
if fluent.IsBufferFull(err) {
if pdebug.Enabled {
pdebug.Printf("Detected full buffer. Stopping Post() loop")
}
break
}
count++
}
sctx, scancel := context.WithCancel(context.Background())
defer scancel()
// Start the server, which should start the writer process
go s.Run(sctx)
<-s.Ready()
// write one more message
var wroteOneMore bool
for i := 1; i < 10; i++ {
if pdebug.Enabled {
pdebug.Printf("Writing one more message...")
}
err := client.Post("tag_name", map[string]interface{}{"foo": i}, fluent.WithSyncAppend(true))
if err == nil {
count++
wroteOneMore = true
break
}
time.Sleep(500 * time.Millisecond)
}
if !assert.True(t, wroteOneMore, "expected to be able to write one more message") {
return
}
// wait for the server to process all of our messages
{
timeout := time.NewTimer(10 * time.Second)
defer timeout.Stop()
tick := time.NewTicker(10 * time.Millisecond)
defer tick.Stop()
for loop := true; loop; {
select {
case <-timeout.C:
t.Errorf("timed out while waiting for the server to process requests")
return // Don't forget to return
case <-tick.C:
if c := s.PayloadCount(); c == count {
t.Logf("Got expected %d messages in the server", c)
loop = false
}
}
}
}
if pdebug.Enabled {
pdebug.Printf("Writing one more after draining")
}
// See if we can still write after the buffer has been drained
s.TruncatePayload()
if !assert.NoError(t, client.Post("tag_name", map[string]interface{}{"foo": 1}, fluent.WithSyncAppend(true)), "writing after the buffer has been drained should succeed") {
return
}
// wait for the server to process all of our messages
{
timeout := time.NewTimer(10 * time.Second)
defer timeout.Stop()
tick := time.NewTicker(10 * time.Millisecond)
defer tick.Stop()
for loop := true; loop; {
select {
case <-timeout.C:
t.Errorf("timed out while waiting for the server to process requests")
case <-tick.C:
if c := s.PayloadCount(); c == 1 {
t.Logf("Got expected %d messages in the server", c)
loop = false
}
}
}
}
client.Close()
}
type badmsgpack struct{}
func (msg *badmsgpack) EncodeMsgpack(_ *msgpack.Encoder) error {
return errors.New(`badmsgpack`)
}
func TestPostSync(t *testing.T) {
for _, syncAppend := range []bool{true, false} {
syncAppend := syncAppend
t.Run("sync="+strconv.FormatBool(syncAppend), func(t *testing.T) {
s, err := newServer(false)
if !assert.NoError(t, err, "newServer should succeed") {
return
}
defer s.Close()
// This is just to stop the server
sctx, scancel := context.WithCancel(context.Background())
defer scancel()
go s.Run(sctx)
<-s.Ready()
client, err := fluent.New(
fluent.WithNetwork(s.Network),
fluent.WithAddress(s.Address),
fluent.WithBufferLimit(1),
)
if !assert.NoError(t, err, "failed to create fluent client") {
return
}
var options []fluent.Option
if syncAppend {
options = append(options, fluent.WithSyncAppend(true))
}
err = client.Post("tag_name", map[string]interface{}{"foo": 1}, options...)
if syncAppend {
if !assert.Error(t, err, "should receive an error") {
return
}
} else {
if !assert.NoError(t, err, "should NOT receive an error") {
return
}
}
err = client.Post("tag_name", &badmsgpack{}, options...)
if syncAppend {
if !assert.Error(t, err, "should receive an error") {
return
}
} else {
if !assert.NoError(t, err, "should NOT receive an error") {
return
}
}
client.Shutdown(context.TODO())
})
}
}
type Payload struct {
Foo string `msgpack:"foo" json:"foo"`
Bar string `msgpack:"bar" json:"bar"`
}
func TestPostRoundtrip(t *testing.T) {
var testcases = []interface{}{
map[string]interface{}{"foo": "bar"},
map[string]interface{}{"fuga": "bar", "hoge": "fuga"},
Payload{Foo: "foo", Bar: "bar"},
&Payload{Foo: "foo", Bar: "bar"},
"hogehoge",
}
for _, buffered := range []bool{true, false} {
buffered := buffered
t.Run(fmt.Sprintf("buffered=%t", buffered), func(t *testing.T) {
var options []fluent.Option
if !buffered {
options = append(options, fluent.WithBuffered(false))
}
for _, marshalerName := range []string{"json", "msgpack", "msgpack-subsecond"} {
var useJSON bool
switch marshalerName {
case "json":
useJSON = true
options = append(options, fluent.WithJSONMarshaler())
case "msgpack":
options = append(options, fluent.WithMsgpackMarshaler())
case "msgpack-subsecond":
options = append(options, fluent.WithMsgpackMarshaler())
options = append(options, fluent.WithSubsecond(true))
}
t.Run("marshaler="+marshalerName, func(t *testing.T) {
// This is used for global cancel/teardown
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
s, err := newServer(useJSON)
if !assert.NoError(t, err, "newServer should succeed") {
return
}
defer s.Close()
// This is just to stop the server
sctx, scancel := context.WithCancel(context.Background())
defer scancel()
go s.Run(sctx)
<-s.Ready()
client, err := fluent.New(
append([]fluent.Option{
fluent.WithNetwork(s.Network),
fluent.WithAddress(s.Address),
}, options...)...,
)
if !assert.NoError(t, err, "failed to create fluent client") {
return
}
defer client.Shutdown(ctx)
for _, data := range testcases {
err := client.Post("tag_name", data, fluent.WithTimestamp(time.Unix(1482493046, 0).UTC()))
if !assert.NoError(t, err, "client.Post should succeed") {
return
}
}
client.Shutdown(ctx)
time.Sleep(time.Second)
scancel()
if pdebug.Enabled {
pdebug.Printf("canceled server context")
}
select {
case <-ctx.Done():
t.Errorf("context canceled: %s", ctx.Err())
return
case <-s.Done():
}
if !assert.Equal(t, s.PayloadCount(), len(testcases)) {
return
}
for i, data := range testcases {
// If data is not a map, we would need to convert it
var payload interface{}
if _, ok := data.(map[string]interface{}); ok {
payload = data
} else {
var marshaler func(interface{}) ([]byte, error)
var unmarshaler func([]byte, interface{}) error
if useJSON {
marshaler = json.Marshal
unmarshaler = json.Unmarshal
} else {
marshaler = msgpack.Marshal
unmarshaler = msgpack.Unmarshal
}
buf, err := marshaler(data)
if !assert.NoError(t, err, "Marshal should succeed") {
return
}
if !assert.NoError(t, unmarshaler(buf, &payload), "Unmarshal should succeed") {
return
}
}
if !assert.Equal(t, &fluent.Message{Tag: "tag_name", Time: fluent.EventTime{Time: time.Unix(1482493046, 0).UTC()}, Record: payload}, s.PayloadAt(i)) {
return
}
}
})
}
})
}
}
func TestPing(t *testing.T) {
for _, buffered := range []bool{true, false} {
buffered := buffered
t.Run(fmt.Sprintf("buffered=%t", buffered), func(t *testing.T) {
t.Run("Ping with no server", func(t *testing.T) {
// find a port that is not available (this may be timing dependent)
var dialer net.Dialer
var port int = 22412
for i := 0; i < 1000; i++ {
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
conn, err := dialer.DialContext(ctx, `net`, fmt.Sprintf(`127.0.0.1:%d`, port))
cancel()
if err == nil {
port++
conn.Close()
continue
}
break
}
client, err := fluent.New(
fluent.WithAddress(fmt.Sprintf(`127.0.0.1:%d`, port)),
fluent.WithBuffered(buffered),
)
if !assert.NoError(t, err, "fluent.New should succeed") {
return
}
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if !assert.Error(t, client.Ping("ping", map[string]interface{}{"host": "localhost"}, fluent.WithContext(ctx)), "Ping should fail") {
return
}
client.Close()
})
t.Run("Ping with active server", func(t *testing.T) {
s, err := newServer(false)
if !assert.NoError(t, err, "newServer should succeed") {
return
}
defer s.Close()
// This is just to stop the server
sctx, scancel := context.WithCancel(context.Background())
defer scancel()
go s.Run(sctx)
<-s.Ready()
client, _ := fluent.New(
fluent.WithNetwork(s.Network),
fluent.WithAddress(s.Address),
fluent.WithBuffered(buffered),
)
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if !assert.NoError(t, client.Ping("ping", map[string]interface{}{"host": "localhost"}, fluent.WithContext(ctx)), "Ping should succeed") {
return
}
client.Shutdown(context.TODO())
// timing sensitive :/ we need to give the server enough time to receive
// the message before canceling it via scancel
time.Sleep(100 * time.Millisecond)
scancel()
<-s.Done()
if !assert.Equal(t, s.PayloadCount(), 1, "expected 1 message") {
return
}
})
})
}
}