Debian Codegraph @

fluent/fluent_test.go

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 package fluent
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "io/ioutil"
10 "net"
11 "reflect"
12 "runtime"
13 "strconv"
14 "strings"
15 "sync"
16 "testing"
17 "time"
18
19 "github.com/tinylib/msgp/msgp"
20 )
21
22 func init() {
23 // randomGenerator points to rand.Uint64 by default. Unfortunately, even when it's
24 // seeded, it produces different values from time to time and thus is not fully
25 // deterministic. This prevents writing stable tests for RequestAck config option.
26 // Thus we need to change it to ensure the hashes are stable during tests.
27 randomGenerator = func() uint64 {
28 return 1
29 }
30 }
31
32 func newTestDialer() *testDialer {
33 return &testDialer{
34 dialCh: make(chan *Conn),
35 }
36 }
37
38 // testDialer is a stub for net.Dialer. It implements the Dial() method used by
39 // the logger to connect to Fluentd. It uses a *Conn channel to let the tests
40 // synchronize with calls to Dial() and let them define what each call to Dial()
41 // should return. This is especially useful for testing edge cases like
42 // transient connection failures.
43 // To help write test cases with succeeding or failing connection dialing, testDialer
44 // provides waitForNextDialing(). Any call to Dial() from the logger should be matched
45 // with a call to waitForNextDialing() in the test cases.
46 //
47 // For instance, to test an async logger that have to dial 4 times before succeeding,
48 // the test should look like this:
49 //
50 // d := newTestDialer() // Create a new stubbed dialer
51 // cfg := Config{
52 // Async: true,
53 // // ...
54 // }
55 // f := newWithDialer(cfg, d) // Create a fluent logger using the stubbed dialer
56 // f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"})
57 //
58 // d.waitForNextDialing(false, false) // 1st dialing attempt fails
59 // d.waitForNextDialing(false, false) // 2nd attempt fails too
60 // d.waitForNextDialing(false, false) // 3rd attempt fails too
61 // d.waitForNextDialing(true, false) // Finally the 4th attempt succeeds
62 //
63 // Note that in the above example, the logger operates in async mode. As such,
64 // a call to Post, PostWithTime or EncodeAndPostData is needed *before* calling
65 // waitForNextDialing(), as in async mode the logger initializes its connection
66 // lazily, in a separate goroutine.
67 // This also means non-async loggers can't be tested exactly the same way, as the
68 // dialing isn't done lazily but during the logger initialization. To test such
69 // case, you have to put the calls to newWithDialer() and to EncodeAndPostData()
70 // into their own goroutine. An example:
71 //
72 // d := newTestDialer() // Create a new stubbed dialer
73 // cfg := Config{
74 // Async: false,
75 // // ...
76 // }
77 // go func() {
78 // f := newWithDialer(cfg, d) // Create a fluent logger using the stubbed dialer
79 // f.Close()
80 // }()
81 //
82 // d.waitForNextDialing(false, false) // 1st dialing attempt fails
83 // d.waitForNextDialing(false, false) // 2nd attempt fails too
84 // d.waitForNextDialing(false, false) // 3rd attempt fails too
85 // d.waitForNextDialing(true, false) // Finally the 4th attempt succeeds
86 //
87 // Moreover, waitForNextDialing() returns a *Conn which extends net.Conn to provide testing
88 // facilities. For instance, you can call waitForNextWrite() on these connections, to
89 // specify how the next Conn.Write() call behaves (e.g. accept or reject it, or make a
90 // specific ack checksum available) and to assert what is sent to Fluentd (when the write
91 // is accepted). Again, any call to Write() on the logger side have to be matched with
92 // a call to waitForNextWrite() in the test cases.
93 //
94 // Here's a full example:
95 //
96 // d := newTestDialer()
97 // cfg := Config{Async: true}
98 //
99 // f := newWithDialer(cfg, d)
100 // f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"})
101 //
102 // conn := d.waitForNextDialing(true, false) // Accept the dialing
103 // conn.waitForNextWrite(false, "") // Discard the 1st attempt to write the message
104 //
105 // conn := d.waitForNextDialing(true, false)
106 // assertReceived(t, // t is *testing.T
107 // conn.waitForNextWrite(true, ""),
108 // `["tag_name",1482493046,{"foo":"bar"},{}]`)
109 //
110 // f.EncodeAndPostData("something_else", time.Unix(1482493050, 0), map[string]string{"bar": "baz"})
111 // assertReceived(t, // t is *testing.T
112 // conn.waitForNextWrite(true, ""),
113 // `["something_else",1482493050,{"bar":"baz"},{}]`)
114 //
115 // In this example, the 1st connection dialing succeeds but the 1st attempt to write the
116 // message is discarded. As the logger discards the connection whenever a message
117 // couldn't be written, it tries to re-dial and thus we need to accept the dialing again.
118 // Then the write is retried and accepted. When a second message is written, the write is
119 // accepted straightaway. Moreover, the messages written to the connections are asserted
120 // using assertReceived() to make sure the logger encodes the messages properly.
121 //
122 // Again, the example above is using async mode thus, calls to f and conn are running in
123 // the same goroutine. However, in sync mode, all calls to f.EncodeAndPostData() as well
124 // as the logger initialization shall be placed in a separate goroutine or the code
125 // allowing the dialing and writing attempts (eg. waitForNextDialing() & waitForNextWrite())
126 // would never be reached.
127 type testDialer struct {
128 dialCh chan *Conn
129 }
130
131 // DialContext is the stubbed method called by the logger to establish the connection to
132 // Fluentd. It is paired with waitForNextDialing().
133 func (d *testDialer) DialContext(ctx context.Context, _, _ string) (net.Conn, error) {
134 // It waits for a *Conn to be pushed into dialCh using waitForNextDialing(). When the
135 // *Conn is nil, the Dial is deemed to fail.
136 select {
137 case conn := <-d.dialCh:
138 if conn == nil {
139 return nil, errors.New("failed to dial")
140 }
141 return conn, nil
142 case <-ctx.Done():
143 return nil, errors.New("failed to dial")
144 }
145 }
146
147 // waitForNextDialing is the method used by test cases below to indicate whether the next
148 // dialing attempt made by the logger should succeed or not. See examples provided on
149 // testDialer docs.
150 func (d *testDialer) waitForNextDialing(accept bool, delayReads bool) *Conn {
151 var conn *Conn
152 if accept {
153 conn = &Conn{
154 nextWriteAttemptCh: make(chan nextWrite),
155 writtenCh: make(chan []byte),
156 }
157
158 if delayReads {
159 conn.delayNextReadCh = make(chan struct{})
160 }
161 }
162
163 d.dialCh <- conn
164 return conn
165 }
166
167 // asserEqual asserts that actual and expected are equivalent, and otherwise
168 // marks the test as failed (t.Error). It uses reflect.DeepEqual internally.
169 func assertEqual(t *testing.T, actual, expected interface{}) {
170 t.Helper()
171 if !reflect.DeepEqual(actual, expected) {
172 t.Errorf("got: '%+v', expected: '%+v'", actual, expected)
173 }
174 }
175
176 // assertReceived is used below by test cases to assert the content written to a *Conn
177 // matches an expected string. This is generally used in conjunction with
178 // Conn.waitForNextWrite().
179 func assertReceived(t *testing.T, rcv []byte, expected string) {
180 t.Helper()
181 assertEqual(t, string(rcv), expected)
182 }
183
184 // Conn extends net.Conn to add channels used to synchronise across goroutines, eg.
185 // between the goroutine doing the dialing (through newWithDialer in sync mode, or the
186 // first message logging in async mode) and the testing goroutine (making calls to
187 // Conn.waitForNextWrite()).
188 // This should be of low importance if you're not trying to understand/change how
189 // waitFor...() methods work. See examples provided in testDialer docs for higher
190 // level details.
191 type Conn struct {
192 net.Conn
193 buf []byte
194 writeDeadline time.Time
195 // nextWriteAttemptCh is used by waitForNextWrite() to let Write() know if the next write
196 // attempt should succeed or fail.
197 nextWriteAttemptCh chan nextWrite
198 // writtenCh is used by Write() to signal to waitForNextWrite() when a write
199 // happened.
200 writtenCh chan []byte
201 // delayNextReadCh is used to delay next conn.Read() attempt when testing ack resp.
202 delayNextReadCh chan struct{}
203 }
204
205 // nextWrite is the struct passed by Conn.waitForNextWrite() to Conn.Write() through
206 // Conn.nextWriteAttemptCh to let Write() know if it should accept or discard the next write
207 // operation and what ack checksum should be made readable from the connection.
208 // This should be of low importance if you're not trying to understand/change how
209 // waitFor...() methods work. See examples provided in testDialer docs for higher
210 // level details.
211 type nextWrite struct {
212 accept bool
213 ack string
214 }
215
216 // waitForNextWrite is the method used to tell how the next write made by the logger
217 // should behave. It can either accept or discard the next write operation. Moreover
218 // an ack checksum can be passed such that the next Write operation will make it
219 // readable from the connection, as the logger will try to read it to ack the Write
220 // operation. See examples provided in testDialer docs.
221 func (c *Conn) waitForNextWrite(accept bool, ack string) []byte {
222 c.nextWriteAttemptCh <- nextWrite{accept, ack}
223 if accept {
224 return <-c.writtenCh
225 }
226 return []byte{}
227 }
228
229 // Read is a stubbed version of net.Conn Read() that returns the ack checksum of the last
230 // Write operation.
231 func (c *Conn) Read(b []byte) (int, error) {
232 if c.delayNextReadCh != nil {
233 select {
234 case _, ok := <-c.delayNextReadCh:
235 if !ok {
236 return 0, errors.New("connection has been closed")
237 }
238 default:
239 }
240 }
241
242 copy(b, c.buf)
243 return len(c.buf), nil
244 }
245
246 // Write is a stubbed version of net.Conn Write(). Its behavior is determined by the last
247 // call to waitForNextWrite(). See examples provided in testDialer docs.
248 func (c *Conn) Write(b []byte) (int, error) {
249 next, ok := nextWrite{true, ""}, true
250 if c.nextWriteAttemptCh != nil {
251 next, ok = <-c.nextWriteAttemptCh
252 }
253 if !next.accept || !ok {
254 return 0, errors.New("transient write failure")
255 }
256
257 // Write the acknowledgment to c.buf to make it available to subsequent
258 // call to Read().
259 c.buf = make([]byte, len(next.ack))
260 copy(c.buf, next.ack)
261
262 // Write the payload received to writtenCh to assert on it.
263 if c.writtenCh != nil {
264 c.writtenCh <- b
265 }
266
267 return len(b), nil
268 }
269
270 func (c *Conn) SetWriteDeadline(t time.Time) error {
271 c.writeDeadline = t
272 return nil
273 }
274
275 // SetReadDeadline is a nop for our test dialer.
276 func (c *Conn) SetReadDeadline(time.Time) error {
277 return nil
278 }
279
280 func (c *Conn) Close() error {
281 if c.delayNextReadCh != nil {
282 close(c.delayNextReadCh)
283 }
284
285 return nil
286 }
287
288 func Test_New_itShouldUseDefaultConfigValuesIfNoOtherProvided(t *testing.T) {
289 f, _ := New(Config{})
290 assertEqual(t, f.Config.FluentPort, defaultPort)
291 assertEqual(t, f.Config.FluentHost, defaultHost)
292 assertEqual(t, f.Config.Timeout, defaultTimeout)
293 assertEqual(t, f.Config.WriteTimeout, defaultWriteTimeout)
294 assertEqual(t, f.Config.BufferLimit, defaultBufferLimit)
295 assertEqual(t, f.Config.FluentNetwork, defaultNetwork)
296 assertEqual(t, f.Config.FluentSocketPath, defaultSocketPath)
297 }
298
299 func Test_New_itShouldUseUnixDomainSocketIfUnixSocketSpecified(t *testing.T) {
300 if runtime.GOOS == "windows" {
301 t.Skip("windows not supported")
302 }
303 socketFile := "/tmp/fluent-logger-golang.sock"
304 network := "unix"
305 l, err := net.Listen(network, socketFile)
306 if err != nil {
307 t.Error(err)
308 return
309 }
310 defer l.Close()
311
312 f, err := New(Config{
313 FluentNetwork: network,
314 FluentSocketPath: socketFile,
315 })
316 if err != nil {
317 t.Error(err)
318 return
319 }
320 defer f.Close()
321 assertEqual(t, f.Config.FluentNetwork, network)
322 assertEqual(t, f.Config.FluentSocketPath, socketFile)
323
324 socketFile = "/tmp/fluent-logger-golang-xxx.sock"
325 network = "unixxxx"
326 fUnknown, err := New(Config{
327 FluentNetwork: network,
328 FluentSocketPath: socketFile,
329 })
330 if _, ok := err.(*ErrUnknownNetwork); !ok {
331 t.Errorf("err type: %T", err)
332 }
333 if err == nil {
334 t.Error(err)
335 fUnknown.Close()
336 return
337 }
338 }
339
340 func Test_New_itShouldUseConfigValuesFromMashalAsJSONArgument(t *testing.T) {
341 f, _ := New(Config{MarshalAsJSON: true})
342 assertEqual(t, f.Config.MarshalAsJSON, true)
343 }
344
345 func Test_MarshalAsMsgpack(t *testing.T) {
346 f := &Fluent{Config: Config{}}
347
348 tag := "tag"
349 data := map[string]string{
350 "foo": "bar",
351 "hoge": "hoge",
352 }
353 tm := time.Unix(1267867237, 0)
354 result, err := f.EncodeData(tag, tm, data)
355 if err != nil {
356 t.Error(err)
357 }
358 actual := string(result.data)
359
360 // map entries are disordered in golang
361 expected1 := "\x94\xA3tag\xD2K\x92\u001Ee\x82\xA3foo\xA3bar\xA4hoge\xA4hoge\x80"
362 expected2 := "\x94\xA3tag\xD2K\x92\u001Ee\x82\xA4hoge\xA4hoge\xA3foo\xA3bar\x80"
363 if actual != expected1 && actual != expected2 {
364 t.Errorf("got %+v,\n except %+v\n or %+v", actual, expected1, expected2)
365 }
366 }
367
368 func Test_SubSecondPrecision(t *testing.T) {
369 // Setup the test subject
370 fluent := &Fluent{
371 Config: Config{
372 SubSecondPrecision: true,
373 },
374 }
375 fluent.conn = &Conn{}
376
377 // Exercise the test subject
378 timestamp := time.Unix(1267867237, 256)
379 encodedData, err := fluent.EncodeData("tag", timestamp, map[string]string{
380 "foo": "bar",
381 })
382 // Assert no encoding errors and that the timestamp has been encoded into
383 // the message as expected.
384 if err != nil {
385 t.Error(err)
386 }
387
388 // 8 bytes timestamp can be represented using ext 8 or fixext 8
389 expected1 := "\x94\xA3tag\xC7\x08\x00K\x92\u001Ee\x00\x00\x01\x00\x81\xA3foo\xA3bar\x80"
390 expected2 := "\x94\xa3tag\xD7\x00K\x92\x1Ee\x00\x00\x01\x00\x81\xA3foo\xA3bar\x80"
391 actual := string(encodedData.data)
392 if actual != expected1 && actual != expected2 {
393 t.Errorf("got %+v,\n except %+v\n or %+v", actual, expected1, expected2)
394 }
395 }
396
397 func Test_MarshalAsJSON(t *testing.T) {
398 f := &Fluent{Config: Config{MarshalAsJSON: true}}
399
400 data := map[string]string{
401 "foo": "bar",
402 "hoge": "hoge",
403 }
404 tm := time.Unix(1267867237, 0)
405 result, err := f.EncodeData("tag", tm, data)
406 if err != nil {
407 t.Error(err)
408 }
409 // json.Encode marshals map keys in the order, so this expectation is safe
410 expected := `["tag",1267867237,{"foo":"bar","hoge":"hoge"},{}]`
411 actual := string(result.data)
412 if actual != expected {
413 t.Errorf("got %s, except %s", actual, expected)
414 }
415 }
416
417 func TestJsonConfig(t *testing.T) {
418 b, err := ioutil.ReadFile(`testdata/config.json`)
419 if err != nil {
420 t.Error(err)
421 }
422 var got Config
423 expect := Config{
424 FluentPort: 8888,
425 FluentHost: "localhost",
426 FluentNetwork: "tcp",
427 FluentSocketPath: "/var/tmp/fluent.sock",
428 Timeout: 3000,
429 WriteTimeout: 6000,
430 BufferLimit: 10,
431 RetryWait: 5,
432 MaxRetry: 3,
433 TagPrefix: "fluent",
434 Async: false,
435 ForceStopAsyncSend: false,
436 MarshalAsJSON: true,
437 }
438
439 err = json.Unmarshal(b, &got)
440 if err != nil {
441 t.Error(err)
442 }
443
444 assertEqual(t, got, expect)
445 }
446
447 func TestPostWithTime(t *testing.T) {
448 testcases := map[string]Config{
449 "with Async": {
450 Async: true,
451 MarshalAsJSON: true,
452 TagPrefix: "acme",
453 },
454 "without Async": {
455 Async: false,
456 MarshalAsJSON: true,
457 TagPrefix: "acme",
458 },
459 }
460
461 for tcname := range testcases {
462 t.Run(tcname, func(t *testing.T) {
463 tc := testcases[tcname]
464 t.Parallel()
465
466 d := newTestDialer()
467 var f *Fluent
468 defer func() {
469 if f != nil {
470 f.Close()
471 }
472 }()
473
474 go func() {
475 var err error
476 if f, err = newWithDialer(tc, d); err != nil {
477 t.Errorf("Unexpected error: %v", err)
478 }
479
480 _ = f.PostWithTime("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"})
481 _ = f.PostWithTime("tag_name", time.Unix(1482493050, 0), map[string]string{"fluentd": "is awesome"})
482 _ = f.PostWithTime("tag_name", time.Unix(1634263200, 0),
483 struct {
484 Welcome string `msg:"welcome"`
485 cannot string
486 }{"to use", "see me"})
487 }()
488
489 conn := d.waitForNextDialing(true, false)
490 assertReceived(t,
491 conn.waitForNextWrite(true, ""),
492 `["acme.tag_name",1482493046,{"foo":"bar"},{}]`)
493
494 assertReceived(t,
495 conn.waitForNextWrite(true, ""),
496 `["acme.tag_name",1482493050,{"fluentd":"is awesome"},{}]`)
497 assertReceived(t,
498 conn.waitForNextWrite(true, ""),
499 `["acme.tag_name",1634263200,{"welcome":"to use"},{}]`)
500 })
501 }
502 }
503
504 func TestReconnectAndResendAfterTransientFailure(t *testing.T) {
505 testcases := map[string]Config{
506 "with Async": {
507 Async: true,
508 MarshalAsJSON: true,
509 },
510 "without Async": {
511 Async: false,
512 MarshalAsJSON: true,
513 },
514 }
515
516 for tcname := range testcases {
517 t.Run(tcname, func(t *testing.T) {
518 tc := testcases[tcname]
519 t.Parallel()
520
521 d := newTestDialer()
522 var f *Fluent
523 defer func() {
524 if f != nil {
525 f.Close()
526 }
527 }()
528
529 go func() {
530 var err error
531 if f, err = newWithDialer(tc, d); err != nil {
532 t.Errorf("Unexpected error: %v", err)
533 }
534
535 _ = f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"})
536 _ = f.EncodeAndPostData("tag_name", time.Unix(1482493050, 0), map[string]string{"fluentd": "is awesome"})
537 }()
538
539 // Accept the first connection dialing and write.
540 conn := d.waitForNextDialing(true, false)
541 assertReceived(t,
542 conn.waitForNextWrite(true, ""),
543 `["tag_name",1482493046,{"foo":"bar"},{}]`)
544
545 // The next write will fail and the next connection dialing will be dropped
546 // to test if the logger is reconnecting as expected.
547 conn.waitForNextWrite(false, "")
548 d.waitForNextDialing(false, false)
549
550 // Next, we allow a new connection to be established and we allow the last message to be written.
551 conn = d.waitForNextDialing(true, false)
552 assertReceived(t,
553 conn.waitForNextWrite(true, ""),
554 `["tag_name",1482493050,{"fluentd":"is awesome"},{}]`)
555 })
556 }
557 }
558
559 func timeout(t *testing.T, duration time.Duration, fn func(), reason string) {
560 done := make(chan struct{})
561 go func() {
562 fn()
563 done <- struct{}{}
564 }()
565
566 select {
567 case <-time.After(duration):
568 t.Fatalf("time out after %s: %s", duration.String(), reason)
569 case <-done:
570 return
571 }
572 }
573
574 func TestCloseOnFailingAsyncConnect(t *testing.T) {
575 testcases := map[string]Config{
576 "with ForceStopAsyncSend and with RequestAck": {
577 Async: true,
578 ForceStopAsyncSend: true,
579 RequestAck: true,
580 },
581 "with ForceStopAsyncSend and without RequestAck": {
582 Async: true,
583 ForceStopAsyncSend: true,
584 RequestAck: false,
585 },
586 "without ForceStopAsyncSend and with RequestAck": {
587 Async: true,
588 ForceStopAsyncSend: false,
589 RequestAck: true,
590 },
591 "without ForceStopAsyncSend and without RequestAck": {
592 Async: true,
593 ForceStopAsyncSend: false,
594 RequestAck: false,
595 },
596 }
597
598 for tcname := range testcases {
599 t.Run(tcname, func(t *testing.T) {
600 tc := testcases[tcname]
601 t.Parallel()
602
603 d := newTestDialer()
604 f, err := newWithDialer(tc, d)
605 if err != nil {
606 t.Errorf("Unexpected error: %v", err)
607 }
608
609 timeout(t, 1*time.Second, func() { f.Close() }, "failed to close the logger")
610 })
611 }
612 }
613
614 func ackRespMsgp(t *testing.T, ack string) string {
615 msg := AckResp{ack}
616 buf := &bytes.Buffer{}
617 ackW := msgp.NewWriter(buf)
618 if err := msg.EncodeMsg(ackW); err != nil {
619 t.Fatalf("Unexpected error: %v", err)
620 }
621 ackW.Flush()
622 return buf.String()
623 }
624
625 func TestNoPanicOnAsyncClose(t *testing.T) {
626 testcases := []struct {
627 name string
628 config Config
629 shouldError bool
630 }{
631 {
632 name: "Channel closed before write",
633 config: Config{
634 Async: true,
635 },
636 shouldError: true,
637 },
638 {
639 name: "Channel not closed at all",
640 config: Config{
641 Async: true,
642 },
643 shouldError: false,
644 },
645 }
646 for _, testcase := range testcases {
647 t.Run(testcase.name, func(t *testing.T) {
648 t.Parallel()
649 d := newTestDialer()
650 f, err := newWithDialer(testcase.config, d)
651 if err != nil {
652 t.Errorf("Unexpected error: %v", err)
653 }
654 if testcase.shouldError {
655 f.Close()
656 }
657 err = f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"})
658 if testcase.shouldError {
659 assertEqual(t, err, fmt.Errorf("fluent#appendBuffer: Logger already closed"))
660 } else {
661 assertEqual(t, err, nil)
662 }
663 })
664 }
665 }
666
667 func TestNoPanicOnAsyncMultipleClose(t *testing.T) {
668 config := Config{
669 Async: true,
670 }
671 d := newTestDialer()
672 f, err := newWithDialer(config, d)
673 if err != nil {
674 t.Errorf("Unexpected error: %v", err)
675 }
676 f.Close()
677 f.Close()
678 }
679
680 func TestCloseOnFailingAsyncReconnect(t *testing.T) {
681 testcases := map[string]Config{
682 "with RequestAck": {
683 Async: true,
684 ForceStopAsyncSend: true,
685 RequestAck: true,
686 },
687
688 "without RequestAck": {
689 Async: true,
690 ForceStopAsyncSend: true,
691 RequestAck: false,
692 },
693 }
694
695 for tcname := range testcases {
696 t.Run(tcname, func(t *testing.T) {
697 tc := testcases[tcname]
698 t.Parallel()
699
700 d := newTestDialer()
701 f, err := newWithDialer(tc, d)
702 if err != nil {
703 t.Errorf("Unexpected error: %v", err)
704 }
705
706 // Send a first message successfully.
707 _ = f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"})
708 conn := d.waitForNextDialing(true, false)
709 conn.waitForNextWrite(true, ackRespMsgp(t, "dgxdWAAAAAABAAAAAAAAAA=="))
710
711 // Then try to send one during a transient connection failure.
712 _ = f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"bar": "baz"})
713 conn.waitForNextWrite(false, "")
714
715 // And add some more logs to the log buffer.
716 _ = f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"acme": "corporation"})
717
718 // But close the logger before it got sent. This is expected to not block.
719 timeout(t, 60*time.Second, func() { f.Close() }, "failed to close the logger")
720 })
721 }
722 }
723
724 func TestCloseWhileWaitingForAckResponse(t *testing.T) {
725 t.Parallel()
726
727 d := newTestDialer()
728 f, err := newWithDialer(Config{
729 Async: true,
730 RequestAck: true,
731 ForceStopAsyncSend: true,
732 }, d)
733 if err != nil {
734 t.Errorf("Unexpected error: %v", err)
735 }
736
737 _ = f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"})
738 conn := d.waitForNextDialing(true, true)
739 conn.waitForNextWrite(true, ackRespMsgp(t, "dgxdWAAAAAABAAAAAAAAAA=="))
740
741 // Test if the logger can really by closed while the client waits for a ack message.
742 timeout(t, 30*time.Second, func() {
743 f.Close()
744 }, "failed to close the logger")
745 }
746
747 func TestSyncWriteAfterCloseFails(t *testing.T) {
748 d := newTestDialer()
749
750 go func() {
751 f, err := newWithDialer(Config{Async: false}, d)
752 if err != nil {
753 t.Errorf("Unexpected error: %v", err)
754 }
755
756 err = f.PostWithTime("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"})
757 if err != nil {
758 t.Errorf("Unexpected error: %v", err)
759 }
760
761 err = f.Close()
762 if err != nil {
763 t.Errorf("Unexpected error: %v", err)
764 }
765
766 // Now let's post some event after Fluent.Close().
767 err = f.PostWithTime("tag_name", time.Unix(1482493050, 0), map[string]string{"foo": "buzz"})
768
769 // The event submission must fail,
770 if err == nil {
771 t.Error("expected an error")
772 }
773
774 // and also must keep Fluentd closed. true equals 1.
775 if f.closed != int32(1) {
776 t.Error("expected Fluentd to be kept closed")
777 }
778 }()
779
780 conn := d.waitForNextDialing(true, false)
781 conn.waitForNextWrite(true, "")
782 }
783
784 func TestPendingChannelThreadSafety(t *testing.T) {
785 f, err := New(Config{
786 Async: true,
787 ForceStopAsyncSend: true,
788 })
789 if err != nil {
790 t.Fatalf("Failed to create logger: %v", err)
791 }
792
793 // Start multiple goroutines posting messages
794 const numGoroutines = 10
795 const messagesPerGoroutine = 100
796 var wg sync.WaitGroup
797 wg.Add(numGoroutines)
798
799 for i := 0; i < numGoroutines; i++ {
800 go func(id int) {
801 defer wg.Done()
802 for j := 0; j < messagesPerGoroutine; j++ {
803 // Post a message
804 err := f.Post("tag", map[string]string{
805 "goroutine": strconv.Itoa(id),
806 "message": strconv.Itoa(j),
807 })
808
809 // If the logger is closed, we expect an error
810 if err != nil && !strings.Contains(err.Error(), "already closed") {
811 t.Errorf("Unexpected error: %v", err)
812 return
813 }
814
815 // Add a small delay to increase the chance of race conditions
816 time.Sleep(time.Millisecond)
817 }
818 }(i)
819 }
820
821 // Wait a bit to let some messages be posted
822 time.Sleep(10 * time.Millisecond)
823
824 // Close the logger while goroutines are still posting
825 f.Close()
826
827 // Wait for all goroutines to finish
828 wg.Wait()
829 }
830
831 func Benchmark_PostWithShortMessage(b *testing.B) {
832 b.StopTimer()
833 d := newTestDialer()
834 f, err := newWithDialer(Config{}, d)
835 if err != nil {
836 panic(err)
837 }
838
839 b.StartTimer()
840 data := map[string]string{"message": "Hello World"}
841 for i := 0; i < b.N; i++ {
842 if err := f.Post("tag", data); err != nil {
843 panic(err)
844 }
845 }
846 }
847
848 func Benchmark_PostWithShortMessageMarshalAsJSON(b *testing.B) {
849 b.StopTimer()
850 f, err := New(Config{MarshalAsJSON: true})
851 if err != nil {
852 panic(err)
853 }
854
855 b.StartTimer()
856 data := map[string]string{"message": "Hello World"}
857 for i := 0; i < b.N; i++ {
858 if err := f.Post("tag", data); err != nil {
859 panic(err)
860 }
861 }
862 }
863
864 func Benchmark_LogWithChunks(b *testing.B) {
865 b.StopTimer()
866 f, err := New(Config{})
867 if err != nil {
868 panic(err)
869 }
870
871 b.StartTimer()
872 data := map[string]string{"msg": "sdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddf"}
873 for i := 0; i < b.N; i++ {
874 if err := f.Post("tag", data); err != nil {
875 panic(err)
876 }
877 }
878 }
879
880 func Benchmark_PostWithStruct(b *testing.B) {
881 b.StopTimer()
882 f, err := New(Config{})
883 if err != nil {
884 panic(err)
885 }
886
887 b.StartTimer()
888 data := struct {
889 Name string `msg:"msgnamename"`
890 }{
891 "john smith",
892 }
893 for i := 0; i < b.N; i++ {
894 if err := f.Post("tag", data); err != nil {
895 panic(err)
896 }
897 }
898 }
899
900 func Benchmark_PostWithStructTaggedAsCodec(b *testing.B) {
901 b.StopTimer()
902 f, err := New(Config{})
903 if err != nil {
904 panic(err)
905 }
906
907 b.StartTimer()
908 data := struct {
909 Name string `codec:"codecname"`
910 }{
911 "john smith",
912 }
913 for i := 0; i < b.N; i++ {
914 if err := f.Post("tag", data); err != nil {
915 panic(err)
916 }
917 }
918 }
919
920 func Benchmark_PostWithStructWithoutTag(b *testing.B) {
921 b.StopTimer()
922 f, err := New(Config{})
923 if err != nil {
924 panic(err)
925 }
926
927 b.StartTimer()
928 data := struct {
929 Name string
930 }{
931 "john smith",
932 }
933 for i := 0; i < b.N; i++ {
934 if err := f.Post("tag", data); err != nil {
935 panic(err)
936 }
937 }
938 }
939
940 func Benchmark_PostWithMapString(b *testing.B) {
941 b.StopTimer()
942 f, err := New(Config{})
943 if err != nil {
944 panic(err)
945 }
946
947 b.StartTimer()
948 data := map[string]string{
949 "foo": "bar",
950 }
951 for i := 0; i < b.N; i++ {
952 if err := f.Post("tag", data); err != nil {
953 panic(err)
954 }
955 }
956 }
957
958 func Benchmark_PostWithMsgpMarshaler(b *testing.B) {
959 b.StopTimer()
960 f, err := New(Config{})
961 if err != nil {
962 panic(err)
963 }
964
965 b.StartTimer()
966 data := &TestMessage{Foo: "bar"}
967 for i := 0; i < b.N; i++ {
968 if err := f.Post("tag", data); err != nil {
969 panic(err)
970 }
971 }
972 }
973
974 func Benchmark_PostWithMapSlice(b *testing.B) {
975 b.StopTimer()
976 f, err := New(Config{})
977 if err != nil {
978 panic(err)
979 }
980
981 b.StartTimer()
982 data := map[string][]int{
983 "foo": {1, 2, 3},
984 }
985 for i := 0; i < b.N; i++ {
986 if err := f.Post("tag", data); err != nil {
987 panic(err)
988 }
989 }
990 }
991
992 func Benchmark_PostWithMapStringAndTime(b *testing.B) {
993 b.StopTimer()
994 f, err := New(Config{})
995 if err != nil {
996 panic(err)
997 }
998
999 b.StartTimer()
1000 data := map[string]string{
1001 "foo": "bar",
1002 }
1003 tm := time.Now()
1004 for i := 0; i < b.N; i++ {
1005 if err := f.PostWithTime("tag", tm, data); err != nil {
1006 panic(err)
1007 }
1008 }
1009 }