| 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_itShouldUseConfigValuesFromArguments(t *testing.T) { |
| 341 |
f, _ := New(Config{FluentPort: 6666, FluentHost: "foobarhost"}) |
| 342 |
assertEqual(t, f.Config.FluentPort, 6666) |
| 343 |
assertEqual(t, f.Config.FluentHost, "foobarhost") |
| 344 |
} |
| 345 |
|
| 346 |
func Test_New_itShouldUseConfigValuesFromMashalAsJSONArgument(t *testing.T) { |
| 347 |
f, _ := New(Config{MarshalAsJSON: true}) |
| 348 |
assertEqual(t, f.Config.MarshalAsJSON, true) |
| 349 |
} |
| 350 |
|
| 351 |
func Test_MarshalAsMsgpack(t *testing.T) { |
| 352 |
f := &Fluent{Config: Config{}} |
| 353 |
|
| 354 |
tag := "tag" |
| 355 |
data := map[string]string{ |
| 356 |
"foo": "bar", |
| 357 |
"hoge": "hoge", |
| 358 |
} |
| 359 |
tm := time.Unix(1267867237, 0) |
| 360 |
result, err := f.EncodeData(tag, tm, data) |
| 361 |
if err != nil { |
| 362 |
t.Error(err) |
| 363 |
} |
| 364 |
actual := string(result.data) |
| 365 |
|
| 366 |
// map entries are disordered in golang |
| 367 |
expected1 := "\x94\xA3tag\xD2K\x92\u001Ee\x82\xA3foo\xA3bar\xA4hoge\xA4hoge\x80" |
| 368 |
expected2 := "\x94\xA3tag\xD2K\x92\u001Ee\x82\xA4hoge\xA4hoge\xA3foo\xA3bar\x80" |
| 369 |
if actual != expected1 && actual != expected2 { |
| 370 |
t.Errorf("got %+v,\n except %+v\n or %+v", actual, expected1, expected2) |
| 371 |
} |
| 372 |
} |
| 373 |
|
| 374 |
func Test_SubSecondPrecision(t *testing.T) { |
| 375 |
// Setup the test subject |
| 376 |
fluent := &Fluent{ |
| 377 |
Config: Config{ |
| 378 |
SubSecondPrecision: true, |
| 379 |
}, |
| 380 |
} |
| 381 |
fluent.conn = &Conn{} |
| 382 |
|
| 383 |
// Exercise the test subject |
| 384 |
timestamp := time.Unix(1267867237, 256) |
| 385 |
encodedData, err := fluent.EncodeData("tag", timestamp, map[string]string{ |
| 386 |
"foo": "bar", |
| 387 |
}) |
| 388 |
// Assert no encoding errors and that the timestamp has been encoded into |
| 389 |
// the message as expected. |
| 390 |
if err != nil { |
| 391 |
t.Error(err) |
| 392 |
} |
| 393 |
|
| 394 |
// 8 bytes timestamp can be represented using ext 8 or fixext 8 |
| 395 |
expected1 := "\x94\xA3tag\xC7\x08\x00K\x92\u001Ee\x00\x00\x01\x00\x81\xA3foo\xA3bar\x80" |
| 396 |
expected2 := "\x94\xa3tag\xD7\x00K\x92\x1Ee\x00\x00\x01\x00\x81\xA3foo\xA3bar\x80" |
| 397 |
actual := string(encodedData.data) |
| 398 |
if actual != expected1 && actual != expected2 { |
| 399 |
t.Errorf("got %+v,\n except %+v\n or %+v", actual, expected1, expected2) |
| 400 |
} |
| 401 |
} |
| 402 |
|
| 403 |
func Test_MarshalAsJSON(t *testing.T) { |
| 404 |
f := &Fluent{Config: Config{MarshalAsJSON: true}} |
| 405 |
|
| 406 |
data := map[string]string{ |
| 407 |
"foo": "bar", |
| 408 |
"hoge": "hoge", |
| 409 |
} |
| 410 |
tm := time.Unix(1267867237, 0) |
| 411 |
result, err := f.EncodeData("tag", tm, data) |
| 412 |
if err != nil { |
| 413 |
t.Error(err) |
| 414 |
} |
| 415 |
// json.Encode marshals map keys in the order, so this expectation is safe |
| 416 |
expected := `["tag",1267867237,{"foo":"bar","hoge":"hoge"},{}]` |
| 417 |
actual := string(result.data) |
| 418 |
if actual != expected { |
| 419 |
t.Errorf("got %s, except %s", actual, expected) |
| 420 |
} |
| 421 |
} |
| 422 |
|
| 423 |
func TestJsonConfig(t *testing.T) { |
| 424 |
b, err := ioutil.ReadFile(`testdata/config.json`) |
| 425 |
if err != nil { |
| 426 |
t.Error(err) |
| 427 |
} |
| 428 |
var got Config |
| 429 |
expect := Config{ |
| 430 |
FluentPort: 8888, |
| 431 |
FluentHost: "localhost", |
| 432 |
FluentNetwork: "tcp", |
| 433 |
FluentSocketPath: "/var/tmp/fluent.sock", |
| 434 |
Timeout: 3000, |
| 435 |
WriteTimeout: 6000, |
| 436 |
BufferLimit: 10, |
| 437 |
RetryWait: 5, |
| 438 |
MaxRetry: 3, |
| 439 |
TagPrefix: "fluent", |
| 440 |
Async: false, |
| 441 |
ForceStopAsyncSend: false, |
| 442 |
MarshalAsJSON: true, |
| 443 |
} |
| 444 |
|
| 445 |
err = json.Unmarshal(b, &got) |
| 446 |
if err != nil { |
| 447 |
t.Error(err) |
| 448 |
} |
| 449 |
|
| 450 |
assertEqual(t, got, expect) |
| 451 |
} |
| 452 |
|
| 453 |
func TestPostWithTime(t *testing.T) { |
| 454 |
testcases := map[string]Config{ |
| 455 |
"with Async": { |
| 456 |
Async: true, |
| 457 |
MarshalAsJSON: true, |
| 458 |
TagPrefix: "acme", |
| 459 |
}, |
| 460 |
"without Async": { |
| 461 |
Async: false, |
| 462 |
MarshalAsJSON: true, |
| 463 |
TagPrefix: "acme", |
| 464 |
}, |
| 465 |
} |
| 466 |
|
| 467 |
for tcname := range testcases { |
| 468 |
t.Run(tcname, func(t *testing.T) { |
| 469 |
tc := testcases[tcname] |
| 470 |
t.Parallel() |
| 471 |
|
| 472 |
d := newTestDialer() |
| 473 |
var f *Fluent |
| 474 |
defer func() { |
| 475 |
if f != nil { |
| 476 |
f.Close() |
| 477 |
} |
| 478 |
}() |
| 479 |
|
| 480 |
go func() { |
| 481 |
var err error |
| 482 |
if f, err = newWithDialer(tc, d); err != nil { |
| 483 |
t.Errorf("Unexpected error: %v", err) |
| 484 |
} |
| 485 |
|
| 486 |
_ = f.PostWithTime("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"}) |
| 487 |
_ = f.PostWithTime("tag_name", time.Unix(1482493050, 0), map[string]string{"fluentd": "is awesome"}) |
| 488 |
_ = f.PostWithTime("tag_name", time.Unix(1634263200, 0), |
| 489 |
struct { |
| 490 |
Welcome string `msg:"welcome"` |
| 491 |
cannot string |
| 492 |
}{"to use", "see me"}) |
| 493 |
}() |
| 494 |
|
| 495 |
conn := d.waitForNextDialing(true, false) |
| 496 |
assertReceived(t, |
| 497 |
conn.waitForNextWrite(true, ""), |
| 498 |
`["acme.tag_name",1482493046,{"foo":"bar"},{}]`) |
| 499 |
|
| 500 |
assertReceived(t, |
| 501 |
conn.waitForNextWrite(true, ""), |
| 502 |
`["acme.tag_name",1482493050,{"fluentd":"is awesome"},{}]`) |
| 503 |
assertReceived(t, |
| 504 |
conn.waitForNextWrite(true, ""), |
| 505 |
`["acme.tag_name",1634263200,{"welcome":"to use"},{}]`) |
| 506 |
}) |
| 507 |
} |
| 508 |
} |
| 509 |
|
| 510 |
func TestReconnectAndResendAfterTransientFailure(t *testing.T) { |
| 511 |
testcases := map[string]Config{ |
| 512 |
"with Async": { |
| 513 |
Async: true, |
| 514 |
MarshalAsJSON: true, |
| 515 |
}, |
| 516 |
"without Async": { |
| 517 |
Async: false, |
| 518 |
MarshalAsJSON: true, |
| 519 |
}, |
| 520 |
} |
| 521 |
|
| 522 |
for tcname := range testcases { |
| 523 |
t.Run(tcname, func(t *testing.T) { |
| 524 |
tc := testcases[tcname] |
| 525 |
t.Parallel() |
| 526 |
|
| 527 |
d := newTestDialer() |
| 528 |
var f *Fluent |
| 529 |
defer func() { |
| 530 |
if f != nil { |
| 531 |
f.Close() |
| 532 |
} |
| 533 |
}() |
| 534 |
|
| 535 |
go func() { |
| 536 |
var err error |
| 537 |
if f, err = newWithDialer(tc, d); err != nil { |
| 538 |
t.Errorf("Unexpected error: %v", err) |
| 539 |
} |
| 540 |
|
| 541 |
_ = f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"}) |
| 542 |
_ = f.EncodeAndPostData("tag_name", time.Unix(1482493050, 0), map[string]string{"fluentd": "is awesome"}) |
| 543 |
}() |
| 544 |
|
| 545 |
// Accept the first connection dialing and write. |
| 546 |
conn := d.waitForNextDialing(true, false) |
| 547 |
assertReceived(t, |
| 548 |
conn.waitForNextWrite(true, ""), |
| 549 |
`["tag_name",1482493046,{"foo":"bar"},{}]`) |
| 550 |
|
| 551 |
// The next write will fail and the next connection dialing will be dropped |
| 552 |
// to test if the logger is reconnecting as expected. |
| 553 |
conn.waitForNextWrite(false, "") |
| 554 |
d.waitForNextDialing(false, false) |
| 555 |
|
| 556 |
// Next, we allow a new connection to be established and we allow the last message to be written. |
| 557 |
conn = d.waitForNextDialing(true, false) |
| 558 |
assertReceived(t, |
| 559 |
conn.waitForNextWrite(true, ""), |
| 560 |
`["tag_name",1482493050,{"fluentd":"is awesome"},{}]`) |
| 561 |
}) |
| 562 |
} |
| 563 |
} |
| 564 |
|
| 565 |
func timeout(t *testing.T, duration time.Duration, fn func(), reason string) { |
| 566 |
done := make(chan struct{}) |
| 567 |
go func() { |
| 568 |
fn() |
| 569 |
done <- struct{}{} |
| 570 |
}() |
| 571 |
|
| 572 |
select { |
| 573 |
case <-time.After(duration): |
| 574 |
t.Fatalf("time out after %s: %s", duration.String(), reason) |
| 575 |
case <-done: |
| 576 |
return |
| 577 |
} |
| 578 |
} |
| 579 |
|
| 580 |
func TestCloseOnFailingAsyncConnect(t *testing.T) { |
| 581 |
testcases := map[string]Config{ |
| 582 |
"with ForceStopAsyncSend and with RequestAck": { |
| 583 |
Async: true, |
| 584 |
ForceStopAsyncSend: true, |
| 585 |
RequestAck: true, |
| 586 |
}, |
| 587 |
"with ForceStopAsyncSend and without RequestAck": { |
| 588 |
Async: true, |
| 589 |
ForceStopAsyncSend: true, |
| 590 |
RequestAck: false, |
| 591 |
}, |
| 592 |
"without ForceStopAsyncSend and with RequestAck": { |
| 593 |
Async: true, |
| 594 |
ForceStopAsyncSend: false, |
| 595 |
RequestAck: true, |
| 596 |
}, |
| 597 |
"without ForceStopAsyncSend and without RequestAck": { |
| 598 |
Async: true, |
| 599 |
ForceStopAsyncSend: false, |
| 600 |
RequestAck: false, |
| 601 |
}, |
| 602 |
} |
| 603 |
|
| 604 |
for tcname := range testcases { |
| 605 |
t.Run(tcname, func(t *testing.T) { |
| 606 |
tc := testcases[tcname] |
| 607 |
t.Parallel() |
| 608 |
|
| 609 |
d := newTestDialer() |
| 610 |
f, err := newWithDialer(tc, d) |
| 611 |
if err != nil { |
| 612 |
t.Errorf("Unexpected error: %v", err) |
| 613 |
} |
| 614 |
|
| 615 |
timeout(t, 1*time.Second, func() { f.Close() }, "failed to close the logger") |
| 616 |
}) |
| 617 |
} |
| 618 |
} |
| 619 |
|
| 620 |
func ackRespMsgp(t *testing.T, ack string) string { |
| 621 |
msg := AckResp{ack} |
| 622 |
buf := &bytes.Buffer{} |
| 623 |
ackW := msgp.NewWriter(buf) |
| 624 |
if err := msg.EncodeMsg(ackW); err != nil { |
| 625 |
t.Fatalf("Unexpected error: %v", err) |
| 626 |
} |
| 627 |
ackW.Flush() |
| 628 |
return buf.String() |
| 629 |
} |
| 630 |
|
| 631 |
func TestNoPanicOnAsyncClose(t *testing.T) { |
| 632 |
testcases := []struct { |
| 633 |
name string |
| 634 |
config Config |
| 635 |
shouldError bool |
| 636 |
}{ |
| 637 |
{ |
| 638 |
name: "Channel closed before write", |
| 639 |
config: Config{ |
| 640 |
Async: true, |
| 641 |
}, |
| 642 |
shouldError: true, |
| 643 |
}, |
| 644 |
{ |
| 645 |
name: "Channel not closed at all", |
| 646 |
config: Config{ |
| 647 |
Async: true, |
| 648 |
}, |
| 649 |
shouldError: false, |
| 650 |
}, |
| 651 |
} |
| 652 |
for _, testcase := range testcases { |
| 653 |
t.Run(testcase.name, func(t *testing.T) { |
| 654 |
t.Parallel() |
| 655 |
d := newTestDialer() |
| 656 |
f, err := newWithDialer(testcase.config, d) |
| 657 |
if err != nil { |
| 658 |
t.Errorf("Unexpected error: %v", err) |
| 659 |
} |
| 660 |
if testcase.shouldError { |
| 661 |
f.Close() |
| 662 |
} |
| 663 |
err = f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"}) |
| 664 |
if testcase.shouldError { |
| 665 |
assertEqual(t, err, fmt.Errorf("fluent#appendBuffer: Logger already closed")) |
| 666 |
} else { |
| 667 |
assertEqual(t, err, nil) |
| 668 |
} |
| 669 |
}) |
| 670 |
} |
| 671 |
} |
| 672 |
|
| 673 |
func TestNoPanicOnAsyncMultipleClose(t *testing.T) { |
| 674 |
config := Config{ |
| 675 |
Async: true, |
| 676 |
} |
| 677 |
d := newTestDialer() |
| 678 |
f, err := newWithDialer(config, d) |
| 679 |
if err != nil { |
| 680 |
t.Errorf("Unexpected error: %v", err) |
| 681 |
} |
| 682 |
f.Close() |
| 683 |
f.Close() |
| 684 |
} |
| 685 |
|
| 686 |
func TestCloseOnFailingAsyncReconnect(t *testing.T) { |
| 687 |
testcases := map[string]Config{ |
| 688 |
"with RequestAck": { |
| 689 |
Async: true, |
| 690 |
ForceStopAsyncSend: true, |
| 691 |
RequestAck: true, |
| 692 |
}, |
| 693 |
|
| 694 |
"without RequestAck": { |
| 695 |
Async: true, |
| 696 |
ForceStopAsyncSend: true, |
| 697 |
RequestAck: false, |
| 698 |
}, |
| 699 |
} |
| 700 |
|
| 701 |
for tcname := range testcases { |
| 702 |
t.Run(tcname, func(t *testing.T) { |
| 703 |
tc := testcases[tcname] |
| 704 |
t.Parallel() |
| 705 |
|
| 706 |
d := newTestDialer() |
| 707 |
f, err := newWithDialer(tc, d) |
| 708 |
if err != nil { |
| 709 |
t.Errorf("Unexpected error: %v", err) |
| 710 |
} |
| 711 |
|
| 712 |
// Send a first message successfully. |
| 713 |
_ = f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"}) |
| 714 |
conn := d.waitForNextDialing(true, false) |
| 715 |
conn.waitForNextWrite(true, ackRespMsgp(t, "dgxdWAAAAAABAAAAAAAAAA==")) |
| 716 |
|
| 717 |
// Then try to send one during a transient connection failure. |
| 718 |
_ = f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"bar": "baz"}) |
| 719 |
conn.waitForNextWrite(false, "") |
| 720 |
|
| 721 |
// And add some more logs to the log buffer. |
| 722 |
_ = f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"acme": "corporation"}) |
| 723 |
|
| 724 |
// But close the logger before it got sent. This is expected to not block. |
| 725 |
timeout(t, 60*time.Second, func() { f.Close() }, "failed to close the logger") |
| 726 |
}) |
| 727 |
} |
| 728 |
} |
| 729 |
|
| 730 |
func TestCloseWhileWaitingForAckResponse(t *testing.T) { |
| 731 |
t.Parallel() |
| 732 |
|
| 733 |
d := newTestDialer() |
| 734 |
f, err := newWithDialer(Config{ |
| 735 |
Async: true, |
| 736 |
RequestAck: true, |
| 737 |
ForceStopAsyncSend: true, |
| 738 |
}, d) |
| 739 |
if err != nil { |
| 740 |
t.Errorf("Unexpected error: %v", err) |
| 741 |
} |
| 742 |
|
| 743 |
_ = f.EncodeAndPostData("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"}) |
| 744 |
conn := d.waitForNextDialing(true, true) |
| 745 |
conn.waitForNextWrite(true, ackRespMsgp(t, "dgxdWAAAAAABAAAAAAAAAA==")) |
| 746 |
|
| 747 |
// Test if the logger can really by closed while the client waits for a ack message. |
| 748 |
timeout(t, 30*time.Second, func() { |
| 749 |
f.Close() |
| 750 |
}, "failed to close the logger") |
| 751 |
} |
| 752 |
|
| 753 |
func TestSyncWriteAfterCloseFails(t *testing.T) { |
| 754 |
d := newTestDialer() |
| 755 |
|
| 756 |
go func() { |
| 757 |
f, err := newWithDialer(Config{Async: false}, d) |
| 758 |
if err != nil { |
| 759 |
t.Errorf("Unexpected error: %v", err) |
| 760 |
} |
| 761 |
|
| 762 |
err = f.PostWithTime("tag_name", time.Unix(1482493046, 0), map[string]string{"foo": "bar"}) |
| 763 |
if err != nil { |
| 764 |
t.Errorf("Unexpected error: %v", err) |
| 765 |
} |
| 766 |
|
| 767 |
err = f.Close() |
| 768 |
if err != nil { |
| 769 |
t.Errorf("Unexpected error: %v", err) |
| 770 |
} |
| 771 |
|
| 772 |
// Now let's post some event after Fluent.Close(). |
| 773 |
err = f.PostWithTime("tag_name", time.Unix(1482493050, 0), map[string]string{"foo": "buzz"}) |
| 774 |
|
| 775 |
// The event submission must fail, |
| 776 |
if err == nil { |
| 777 |
t.Error("expected an error") |
| 778 |
} |
| 779 |
|
| 780 |
// and also must keep Fluentd closed. true equals 1. |
| 781 |
if f.closed != int32(1) { |
| 782 |
t.Error("expected Fluentd to be kept closed") |
| 783 |
} |
| 784 |
}() |
| 785 |
|
| 786 |
conn := d.waitForNextDialing(true, false) |
| 787 |
conn.waitForNextWrite(true, "") |
| 788 |
} |
| 789 |
|
| 790 |
func TestPendingChannelThreadSafety(t *testing.T) { |
| 791 |
f, err := New(Config{ |
| 792 |
Async: true, |
| 793 |
ForceStopAsyncSend: true, |
| 794 |
}) |
| 795 |
if err != nil { |
| 796 |
t.Fatalf("Failed to create logger: %v", err) |
| 797 |
} |
| 798 |
|
| 799 |
// Start multiple goroutines posting messages |
| 800 |
const numGoroutines = 10 |
| 801 |
const messagesPerGoroutine = 100 |
| 802 |
var wg sync.WaitGroup |
| 803 |
wg.Add(numGoroutines) |
| 804 |
|
| 805 |
for i := 0; i < numGoroutines; i++ { |
| 806 |
go func(id int) { |
| 807 |
defer wg.Done() |
| 808 |
for j := 0; j < messagesPerGoroutine; j++ { |
| 809 |
// Post a message |
| 810 |
err := f.Post("tag", map[string]string{ |
| 811 |
"goroutine": strconv.Itoa(id), |
| 812 |
"message": strconv.Itoa(j), |
| 813 |
}) |
| 814 |
|
| 815 |
// If the logger is closed, we expect an error |
| 816 |
if err != nil && !strings.Contains(err.Error(), "already closed") { |
| 817 |
t.Errorf("Unexpected error: %v", err) |
| 818 |
return |
| 819 |
} |
| 820 |
|
| 821 |
// Add a small delay to increase the chance of race conditions |
| 822 |
time.Sleep(time.Millisecond) |
| 823 |
} |
| 824 |
}(i) |
| 825 |
} |
| 826 |
|
| 827 |
// Wait a bit to let some messages be posted |
| 828 |
time.Sleep(10 * time.Millisecond) |
| 829 |
|
| 830 |
// Close the logger while goroutines are still posting |
| 831 |
f.Close() |
| 832 |
|
| 833 |
// Wait for all goroutines to finish |
| 834 |
wg.Wait() |
| 835 |
} |
| 836 |
|
| 837 |
func Benchmark_PostWithShortMessage(b *testing.B) { |
| 838 |
b.StopTimer() |
| 839 |
d := newTestDialer() |
| 840 |
f, err := newWithDialer(Config{}, d) |
| 841 |
if err != nil { |
| 842 |
panic(err) |
| 843 |
} |
| 844 |
|
| 845 |
b.StartTimer() |
| 846 |
data := map[string]string{"message": "Hello World"} |
| 847 |
for i := 0; i < b.N; i++ { |
| 848 |
if err := f.Post("tag", data); err != nil { |
| 849 |
panic(err) |
| 850 |
} |
| 851 |
} |
| 852 |
} |
| 853 |
|
| 854 |
func Benchmark_PostWithShortMessageMarshalAsJSON(b *testing.B) { |
| 855 |
b.StopTimer() |
| 856 |
f, err := New(Config{MarshalAsJSON: true}) |
| 857 |
if err != nil { |
| 858 |
panic(err) |
| 859 |
} |
| 860 |
|
| 861 |
b.StartTimer() |
| 862 |
data := map[string]string{"message": "Hello World"} |
| 863 |
for i := 0; i < b.N; i++ { |
| 864 |
if err := f.Post("tag", data); err != nil { |
| 865 |
panic(err) |
| 866 |
} |
| 867 |
} |
| 868 |
} |
| 869 |
|
| 870 |
func Benchmark_LogWithChunks(b *testing.B) { |
| 871 |
b.StopTimer() |
| 872 |
f, err := New(Config{}) |
| 873 |
if err != nil { |
| 874 |
panic(err) |
| 875 |
} |
| 876 |
|
| 877 |
b.StartTimer() |
| 878 |
data := map[string]string{"msg": "sdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddfsdfsdsdfdsfdsddddf"} |
| 879 |
for i := 0; i < b.N; i++ { |
| 880 |
if err := f.Post("tag", data); err != nil { |
| 881 |
panic(err) |
| 882 |
} |
| 883 |
} |
| 884 |
} |
| 885 |
|
| 886 |
func Benchmark_PostWithStruct(b *testing.B) { |
| 887 |
b.StopTimer() |
| 888 |
f, err := New(Config{}) |
| 889 |
if err != nil { |
| 890 |
panic(err) |
| 891 |
} |
| 892 |
|
| 893 |
b.StartTimer() |
| 894 |
data := struct { |
| 895 |
Name string `msg:"msgnamename"` |
| 896 |
}{ |
| 897 |
"john smith", |
| 898 |
} |
| 899 |
for i := 0; i < b.N; i++ { |
| 900 |
if err := f.Post("tag", data); err != nil { |
| 901 |
panic(err) |
| 902 |
} |
| 903 |
} |
| 904 |
} |
| 905 |
|
| 906 |
func Benchmark_PostWithStructTaggedAsCodec(b *testing.B) { |
| 907 |
b.StopTimer() |
| 908 |
f, err := New(Config{}) |
| 909 |
if err != nil { |
| 910 |
panic(err) |
| 911 |
} |
| 912 |
|
| 913 |
b.StartTimer() |
| 914 |
data := struct { |
| 915 |
Name string `codec:"codecname"` |
| 916 |
}{ |
| 917 |
"john smith", |
| 918 |
} |
| 919 |
for i := 0; i < b.N; i++ { |
| 920 |
if err := f.Post("tag", data); err != nil { |
| 921 |
panic(err) |
| 922 |
} |
| 923 |
} |
| 924 |
} |
| 925 |
|
| 926 |
func Benchmark_PostWithStructWithoutTag(b *testing.B) { |
| 927 |
b.StopTimer() |
| 928 |
f, err := New(Config{}) |
| 929 |
if err != nil { |
| 930 |
panic(err) |
| 931 |
} |
| 932 |
|
| 933 |
b.StartTimer() |
| 934 |
data := struct { |
| 935 |
Name string |
| 936 |
}{ |
| 937 |
"john smith", |
| 938 |
} |
| 939 |
for i := 0; i < b.N; i++ { |
| 940 |
if err := f.Post("tag", data); err != nil { |
| 941 |
panic(err) |
| 942 |
} |
| 943 |
} |
| 944 |
} |
| 945 |
|
| 946 |
func Benchmark_PostWithMapString(b *testing.B) { |
| 947 |
b.StopTimer() |
| 948 |
f, err := New(Config{}) |
| 949 |
if err != nil { |
| 950 |
panic(err) |
| 951 |
} |
| 952 |
|
| 953 |
b.StartTimer() |
| 954 |
data := map[string]string{ |
| 955 |
"foo": "bar", |
| 956 |
} |
| 957 |
for i := 0; i < b.N; i++ { |
| 958 |
if err := f.Post("tag", data); err != nil { |
| 959 |
panic(err) |
| 960 |
} |
| 961 |
} |
| 962 |
} |
| 963 |
|
| 964 |
func Benchmark_PostWithMsgpMarshaler(b *testing.B) { |
| 965 |
b.StopTimer() |
| 966 |
f, err := New(Config{}) |
| 967 |
if err != nil { |
| 968 |
panic(err) |
| 969 |
} |
| 970 |
|
| 971 |
b.StartTimer() |
| 972 |
data := &TestMessage{Foo: "bar"} |
| 973 |
for i := 0; i < b.N; i++ { |
| 974 |
if err := f.Post("tag", data); err != nil { |
| 975 |
panic(err) |
| 976 |
} |
| 977 |
} |
| 978 |
} |
| 979 |
|
| 980 |
func Benchmark_PostWithMapSlice(b *testing.B) { |
| 981 |
b.StopTimer() |
| 982 |
f, err := New(Config{}) |
| 983 |
if err != nil { |
| 984 |
panic(err) |
| 985 |
} |
| 986 |
|
| 987 |
b.StartTimer() |
| 988 |
data := map[string][]int{ |
| 989 |
"foo": {1, 2, 3}, |
| 990 |
} |
| 991 |
for i := 0; i < b.N; i++ { |
| 992 |
if err := f.Post("tag", data); err != nil { |
| 993 |
panic(err) |
| 994 |
} |
| 995 |
} |
| 996 |
} |
| 997 |
|
| 998 |
func Benchmark_PostWithMapStringAndTime(b *testing.B) { |
| 999 |
b.StopTimer() |
| 1000 |
f, err := New(Config{}) |
| 1001 |
if err != nil { |
| 1002 |
panic(err) |
| 1003 |
} |
| 1004 |
|
| 1005 |
b.StartTimer() |
| 1006 |
data := map[string]string{ |
| 1007 |
"foo": "bar", |
| 1008 |
} |
| 1009 |
tm := time.Now() |
| 1010 |
for i := 0; i < b.N; i++ { |
| 1011 |
if err := f.PostWithTime("tag", tm, data); err != nil { |
| 1012 |
panic(err) |
| 1013 |
} |
| 1014 |
} |
| 1015 |
} |