Debian Codegraph @

fluent/fluent_test.go

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