Debian Codegraph @

fluent/fluent.go

raw symbols SCIP
1 package fluent
2
3 import (
4 "bytes"
5 "context"
6 "crypto/tls"
7 "encoding/base64"
8 "encoding/binary"
9 "encoding/json"
10 "errors"
11 "fmt"
12 "math"
13 "math/rand"
14 "net"
15 "os"
16 "reflect"
17 "strconv"
18 "sync"
19 "sync/atomic"
20 "time"
21
22 "github.com/tinylib/msgp/msgp"
23 )
24
25 const (
26 defaultHost = "127.0.0.1"
27 defaultNetwork = "tcp"
28 defaultSocketPath = ""
29 defaultPort = 24224
30 defaultTimeout = 3 * time.Second
31 defaultWriteTimeout = time.Duration(0) // Write() will not time out
32 defaultBufferLimit = 8 * 1024
33 defaultRetryWait = 500
34 defaultMaxRetryWait = 60000
35 defaultMaxRetry = 13
36 defaultReconnectWaitIncreRate = 1.5
37
38 // Default value whether to skip checking insecure certs on TLS connections.
39 defaultTlsInsecureSkipVerify = false
40 defaultReadTimeout = time.Duration(0) // Read() will not time out
41 )
42
43 // randomGenerator is used by getUniqueId to generate ack hashes. Its value is replaced
44 // during tests with a deterministic function.
45 var randomGenerator = rand.Uint64
46
47 type Config struct {
48 FluentPort int `json:"fluent_port"`
49 FluentHost string `json:"fluent_host"`
50 FluentNetwork string `json:"fluent_network"`
51 FluentSocketPath string `json:"fluent_socket_path"`
52 Timeout time.Duration `json:"timeout"`
53 WriteTimeout time.Duration `json:"write_timeout"`
54 BufferLimit int `json:"buffer_limit"`
55 RetryWait int `json:"retry_wait"`
56 MaxRetry int `json:"max_retry"`
57 MaxRetryWait int `json:"max_retry_wait"`
58 TagPrefix string `json:"tag_prefix"`
59 Async bool `json:"async"`
60 ForceStopAsyncSend bool `json:"force_stop_async_send"`
61 AsyncResultCallback func(data []byte, err error)
62 // Deprecated: Use Async instead
63 AsyncConnect bool `json:"async_connect"`
64 MarshalAsJSON bool `json:"marshal_as_json"`
65
66 // AsyncReconnectInterval defines the interval (ms) at which the connection
67 // to the fluentd-address is re-established. This option is useful if the address
68 // may resolve to one or more IP addresses, e.g. a Consul service address.
69 AsyncReconnectInterval int `json:"async_reconnect_interval"`
70
71 // Sub-second precision timestamps are only possible for those using fluentd
72 // v0.14+ and serializing their messages with msgpack.
73 SubSecondPrecision bool `json:"sub_second_precision"`
74
75 // RequestAck sends the chunk option with a unique ID. The server will
76 // respond with an acknowledgement. This option improves the reliability
77 // of the message transmission.
78 RequestAck bool `json:"request_ack"`
79
80 // Flag to skip verifying insecure certs on TLS connections
81 TlsInsecureSkipVerify bool `json:"tls_insecure_skip_verify"`
82
83 // ReadTimeout specifies the timeout on reads. Currently only acks are read.
84 ReadTimeout time.Duration `json:"read_timeout"`
85 }
86
87 type ErrUnknownNetwork struct {
88 network string
89 }
90
91 func (e *ErrUnknownNetwork) Error() string {
92 return "unknown network " + e.network
93 }
94
95 func NewErrUnknownNetwork(network string) error {
96 return &ErrUnknownNetwork{network}
97 }
98
99 type msgToSend struct {
100 data []byte
101 ack string
102 }
103
104 type Fluent struct {
105 Config
106
107 dialer dialer
108 // cancelDialings is used by Close() to stop any in-progress dialing.
109 cancelDialings context.CancelFunc
110 pending chan *msgToSend
111 // closed indicates if the connection is open or closed.
112 // 0 = open (false), 1 = closed (true). Since the code is built in CI with
113 // golang < 1.19, we're using atomic int32 here. Otherwise, atomic.Bool
114 // could have been used.
115 closed int32
116 wg sync.WaitGroup
117
118 // time at which the most recent connection to fluentd-address was established.
119 latestReconnectTime time.Time
120
121 muconn sync.RWMutex
122 pendingMutex sync.RWMutex
123 conn net.Conn
124 }
125
126 type dialer interface {
127 DialContext(ctx context.Context, network, address string) (net.Conn, error)
128 }
129
130 // New creates a new Logger.
131 func New(config Config) (*Fluent, error) {
132 if config.Timeout == 0 {
133 config.Timeout = defaultTimeout
134 }
135 return newWithDialer(config, &net.Dialer{
136 Timeout: config.Timeout,
137 })
138 }
139
140 func newWithDialer(config Config, d dialer) (f *Fluent, err error) {
141 if config.FluentNetwork == "" {
142 config.FluentNetwork = defaultNetwork
143 }
144 if config.FluentHost == "" {
145 config.FluentHost = defaultHost
146 }
147 if config.FluentPort == 0 {
148 config.FluentPort = defaultPort
149 }
150 if config.FluentSocketPath == "" {
151 config.FluentSocketPath = defaultSocketPath
152 }
153 if config.WriteTimeout == 0 {
154 config.WriteTimeout = defaultWriteTimeout
155 }
156 if config.ReadTimeout == 0 {
157 config.ReadTimeout = defaultReadTimeout
158 }
159 if config.BufferLimit == 0 {
160 config.BufferLimit = defaultBufferLimit
161 }
162 if config.RetryWait == 0 {
163 config.RetryWait = defaultRetryWait
164 }
165 if config.MaxRetry == 0 {
166 config.MaxRetry = defaultMaxRetry
167 }
168 if config.MaxRetryWait == 0 {
169 config.MaxRetryWait = defaultMaxRetryWait
170 }
171 if !config.TlsInsecureSkipVerify {
172 config.TlsInsecureSkipVerify = defaultTlsInsecureSkipVerify
173 }
174 if config.AsyncConnect {
175 fmt.Fprintf(os.Stderr, "fluent#New: AsyncConnect is now deprecated, please use Async instead")
176 config.Async = config.Async || config.AsyncConnect
177 }
178
179 if config.Async {
180 ctx, cancel := context.WithCancel(context.Background())
181
182 f = &Fluent{
183 Config: config,
184 dialer: d,
185 cancelDialings: cancel,
186 pending: make(chan *msgToSend, config.BufferLimit),
187 muconn: sync.RWMutex{},
188 pendingMutex: sync.RWMutex{},
189 }
190
191 f.wg.Add(1)
192 go f.run(ctx)
193 } else {
194 f = &Fluent{
195 Config: config,
196 dialer: d,
197 muconn: sync.RWMutex{},
198 pendingMutex: sync.RWMutex{},
199 }
200 err = f.connect(context.Background())
201 }
202 return
203 }
204
205 // Post writes the output for a logging event.
206 //
207 // Examples:
208 //
209 // // send map[string]
210 // mapStringData := map[string]string{
211 // "foo": "bar",
212 // }
213 // f.Post("tag_name", mapStringData)
214 //
215 // // send message with specified time
216 // mapStringData := map[string]string{
217 // "foo": "bar",
218 // }
219 // tm := time.Now()
220 // f.PostWithTime("tag_name", tm, mapStringData)
221 //
222 // // send struct
223 // structData := struct {
224 // Name string `msg:"name"`
225 // } {
226 // "john smith",
227 // }
228 // f.Post("tag_name", structData)
229 func (f *Fluent) Post(tag string, message interface{}) error {
230 timeNow := time.Now()
231 return f.PostWithTime(tag, timeNow, message)
232 }
233
234 func (f *Fluent) PostWithTime(tag string, tm time.Time, message interface{}) error {
235 if len(f.TagPrefix) > 0 {
236 tag = f.TagPrefix + "." + tag
237 }
238
239 if m, ok := message.(msgp.Marshaler); ok {
240 return f.EncodeAndPostData(tag, tm, m)
241 }
242
243 msg := reflect.ValueOf(message)
244 msgtype := msg.Type()
245
246 if msgtype.Kind() == reflect.Struct {
247 // message should be tagged by "codec" or "msg"
248 kv := make(map[string]interface{})
249 fields := msgtype.NumField()
250 for i := 0; i < fields; i++ {
251 field := msgtype.Field(i)
252 value := msg.FieldByIndex(field.Index)
253 // ignore unexported fields
254 if !value.CanInterface() {
255 continue
256 }
257 name := field.Name
258 if n1 := field.Tag.Get("msg"); n1 != "" {
259 name = n1
260 } else if n2 := field.Tag.Get("codec"); n2 != "" {
261 name = n2
262 }
263 kv[name] = value.Interface()
264 }
265 return f.EncodeAndPostData(tag, tm, kv)
266 }
267
268 if msgtype.Kind() != reflect.Map {
269 return errors.New("fluent#PostWithTime: message must be a map")
270 } else if msgtype.Key().Kind() != reflect.String {
271 return errors.New("fluent#PostWithTime: map keys must be strings")
272 }
273
274 kv := make(map[string]interface{})
275 for _, k := range msg.MapKeys() {
276 kv[k.String()] = msg.MapIndex(k).Interface()
277 }
278
279 return f.EncodeAndPostData(tag, tm, kv)
280 }
281
282 func (f *Fluent) EncodeAndPostData(tag string, tm time.Time, message interface{}) error {
283 var msg *msgToSend
284 var err error
285 if msg, err = f.EncodeData(tag, tm, message); err != nil {
286 return fmt.Errorf("fluent#EncodeAndPostData: can't convert '%#v' to msgpack:%w", message, err)
287 }
288 return f.postRawData(msg)
289 }
290
291 // Deprecated: Use EncodeAndPostData instead
292 func (f *Fluent) PostRawData(msg *msgToSend) {
293 f.postRawData(msg)
294 }
295
296 func (f *Fluent) postRawData(msg *msgToSend) error {
297 if f.Config.Async {
298 return f.appendBuffer(msg)
299 }
300
301 // Synchronous write
302 if atomic.LoadInt32(&f.closed) == 1 {
303 return fmt.Errorf("fluent#postRawData: Logger already closed")
304 }
305 return f.writeWithRetry(context.Background(), msg)
306 }
307
308 // For sending forward protocol adopted JSON
309 type MessageChunk struct {
310 message Message
311 }
312
313 // Golang default marshaler does not support
314 // ["value", "value2", {"key":"value"}] style marshaling.
315 // So, it should write JSON marshaler by hand.
316 func (chunk *MessageChunk) MarshalJSON() ([]byte, error) {
317 data, err := json.Marshal(chunk.message.Record)
318 if err != nil {
319 return nil, err
320 }
321 option, err := json.Marshal(chunk.message.Option)
322 if err != nil {
323 return nil, err
324 }
325 return []byte(fmt.Sprintf(`["%s",%d,%s,%s]`, chunk.message.Tag,
326 chunk.message.Time, data, option)), err
327 }
328
329 // getUniqueID returns a base64 encoded unique ID that can be used for chunk/ack
330 // mechanism, see
331 // https://github.com/fluent/fluentd/wiki/Forward-Protocol-Specification-v1#option
332 func getUniqueID(timeUnix int64) (string, error) {
333 buf := bytes.NewBuffer(nil)
334 enc := base64.NewEncoder(base64.StdEncoding, buf)
335 if err := binary.Write(enc, binary.LittleEndian, timeUnix); err != nil {
336 enc.Close()
337 return "", err
338 }
339 if err := binary.Write(enc, binary.LittleEndian, randomGenerator()); err != nil {
340 enc.Close()
341 return "", err
342 }
343 // encoder needs to be closed before buf.String(), defer does not work
344 // here
345 enc.Close()
346 return buf.String(), nil
347 }
348
349 func (f *Fluent) EncodeData(tag string, tm time.Time, message interface{}) (msg *msgToSend, err error) {
350 option := make(map[string]string)
351 msg = &msgToSend{}
352 timeUnix := tm.Unix()
353 if f.Config.RequestAck {
354 var err error
355 msg.ack, err = getUniqueID(timeUnix)
356 if err != nil {
357 return nil, err
358 }
359 option["chunk"] = msg.ack
360 }
361 if f.Config.MarshalAsJSON {
362 m := Message{Tag: tag, Time: timeUnix, Record: message, Option: option}
363 chunk := &MessageChunk{message: m}
364 msg.data, err = json.Marshal(chunk)
365 } else if f.Config.SubSecondPrecision {
366 m := &MessageExt{Tag: tag, Time: EventTime(tm), Record: message, Option: option}
367 msg.data, err = m.MarshalMsg(nil)
368 } else {
369 m := &Message{Tag: tag, Time: timeUnix, Record: message, Option: option}
370 msg.data, err = m.MarshalMsg(nil)
371 }
372 return
373 }
374
375 // Close closes the connection, waiting for pending logs to be sent. If the client is
376 // running in async mode, the run() goroutine exits before Close() returns.
377 func (f *Fluent) Close() (err error) {
378 if f.Config.Async {
379 // Use a mutex to ensure thread safety when closing the channel
380 f.pendingMutex.Lock()
381
382 if atomic.LoadInt32(&f.closed) == 1 {
383 f.pendingMutex.Unlock()
384 return nil
385 }
386 atomic.StoreInt32(&f.closed, 1)
387
388 if f.Config.ForceStopAsyncSend {
389 f.cancelDialings()
390 }
391
392 close(f.pending)
393 f.pendingMutex.Unlock()
394
395 // If ForceStopAsyncSend is false, all logs in the channel have to be sent
396 // before closing the connection. At this point closed is true so no more
397 // logs are written to the channel and f.pending has been closed, so run()
398 // goroutine will exit as soon as all logs in the channel are sent.
399 if !f.Config.ForceStopAsyncSend {
400 f.wg.Wait()
401 }
402 }
403
404 f.syncClose(true)
405
406 // If ForceStopAsyncSend is true, we shall close the connection before waiting for
407 // run() goroutine to exit to be sure we aren't waiting on ack message that might
408 // never come (eg. because fluentd server is down). However we want to be sure the
409 // run() goroutine stops before returning from Close().
410 if f.Config.ForceStopAsyncSend {
411 f.wg.Wait()
412 }
413 return
414 }
415
416 // appendBuffer appends data to buffer with lock.
417 func (f *Fluent) appendBuffer(msg *msgToSend) error {
418 if atomic.LoadInt32(&f.closed) == 1 {
419 return fmt.Errorf("fluent#appendBuffer: Logger already closed")
420 }
421
422 // Use a mutex to ensure thread safety when writing to the channel
423 f.pendingMutex.Lock()
424 defer f.pendingMutex.Unlock()
425
426 // Check again after acquiring the lock
427 if atomic.LoadInt32(&f.closed) == 1 {
428 return fmt.Errorf("fluent#appendBuffer: Logger already closed")
429 }
430
431 select {
432 case f.pending <- msg:
433 default:
434 return fmt.Errorf("fluent#appendBuffer: Buffer full, limit %v", f.Config.BufferLimit)
435 }
436 return nil
437 }
438
439 func (f *Fluent) syncClose(setClosed bool) {
440 f.muconn.Lock()
441 defer f.muconn.Unlock()
442
443 if setClosed {
444 atomic.StoreInt32(&f.closed, 1)
445 }
446
447 f.close()
448 }
449
450 // close closes the connection. Callers should take care of locking muconn first.
451 func (f *Fluent) close() {
452 if f.conn != nil {
453 f.conn.Close()
454 f.conn = nil
455 }
456 }
457
458 // connect establishes a new connection using the specified transport. Caller should
459 // take care of locking muconn first.
460 func (f *Fluent) connect(ctx context.Context) (err error) {
461 switch f.Config.FluentNetwork {
462 case "tcp":
463 f.conn, err = f.dialer.DialContext(ctx,
464 f.Config.FluentNetwork,
465 f.Config.FluentHost+":"+strconv.Itoa(f.Config.FluentPort))
466 case "tls":
467 tlsConfig := &tls.Config{InsecureSkipVerify: f.Config.TlsInsecureSkipVerify}
468 f.conn, err = tls.DialWithDialer(
469 &net.Dialer{Timeout: f.Config.Timeout},
470 "tcp",
471 f.Config.FluentHost+":"+strconv.Itoa(f.Config.FluentPort), tlsConfig,
472 )
473 case "unix":
474 f.conn, err = f.dialer.DialContext(ctx,
475 f.Config.FluentNetwork,
476 f.Config.FluentSocketPath)
477 default:
478 err = NewErrUnknownNetwork(f.Config.FluentNetwork)
479 }
480
481 if err == nil {
482 f.latestReconnectTime = time.Now()
483 }
484
485 return err
486 }
487
488 var errIsClosing = errors.New("fluent logger is closing")
489
490 func (f *Fluent) syncConnectWithRetry(ctx context.Context) error {
491 f.muconn.Lock()
492 defer f.muconn.Unlock()
493
494 if f.conn == nil {
495 return f.connectWithRetry(ctx)
496 }
497
498 return nil
499 }
500
501 // Caller should take care of locking muconn first.
502 func (f *Fluent) connectWithRetry(ctx context.Context) error {
503 // A Time channel is used instead of time.Sleep() to avoid blocking this
504 // goroutine during way too much time (because of the exponential back-off
505 // retry).
506 // time.NewTimer() is used instead of time.After() to avoid leaking the
507 // timer channel (cf. https://pkg.go.dev/time#After).
508 timeout := time.NewTimer(time.Duration(0))
509 defer func() {
510 // timeout.Stop() is called in a function literal instead of being
511 // defered directly as it's re-assigned below when the retry loop spins.
512 timeout.Stop()
513 }()
514
515 for i := 0; i < f.Config.MaxRetry; i++ {
516 select {
517 case <-timeout.C:
518 err := f.connect(ctx)
519 if err == nil {
520 return nil
521 }
522
523 if _, ok := err.(*ErrUnknownNetwork); ok {
524 return err
525 }
526 if err == context.Canceled {
527 return errIsClosing
528 }
529
530 waitTime := f.Config.RetryWait * e(defaultReconnectWaitIncreRate, float64(i-1))
531 if waitTime > f.Config.MaxRetryWait {
532 waitTime = f.Config.MaxRetryWait
533 }
534
535 timeout = time.NewTimer(time.Duration(waitTime) * time.Millisecond)
536 case <-ctx.Done():
537 return errIsClosing
538 }
539 }
540
541 return fmt.Errorf("could not connect to fluentd after %d retries", f.Config.MaxRetry)
542 }
543
544 // run is the goroutine used to unqueue and write logs in async mode. That
545 // goroutine is meant to run during the whole life of the Fluent logger.
546 func (f *Fluent) run(ctx context.Context) {
547 for {
548 select {
549 case entry, ok := <-f.pending:
550 // The context is cancelled before f.pending only when ForceStopAsyncSend
551 // is enabled. Otherwise, f.pending is closed when Close() is called.
552 if !ok {
553 f.wg.Done()
554 return
555 }
556
557 if f.AsyncReconnectInterval > 0 {
558 if time.Since(f.latestReconnectTime) > time.Duration(f.AsyncReconnectInterval)*time.Millisecond {
559 f.muconn.Lock()
560 f.close()
561 f.connectWithRetry(ctx)
562 f.muconn.Unlock()
563 }
564 }
565
566 err := f.writeWithRetry(ctx, entry)
567 if err != nil && err != errIsClosing {
568 fmt.Fprintf(os.Stderr, "[%s] Unable to send logs to fluentd, reconnecting...\n", time.Now().Format(time.RFC3339))
569 }
570 if f.AsyncResultCallback != nil {
571 var data []byte
572 if entry != nil {
573 data = entry.data
574 }
575 f.AsyncResultCallback(data, err)
576 }
577 case <-ctx.Done():
578 // Context was canceled, which means ForceStopAsyncSend was enabled
579 fmt.Fprintf(os.Stderr, "[%s] Discarding queued events...\n", time.Now().Format(time.RFC3339))
580 f.wg.Done()
581 return
582 }
583 }
584 }
585
586 func e(x, y float64) int {
587 return int(math.Pow(x, y))
588 }
589
590 func (f *Fluent) writeWithRetry(ctx context.Context, msg *msgToSend) error {
591 for i := 0; i < f.Config.MaxRetry; i++ {
592 if retry, err := f.write(ctx, msg); !retry {
593 return err
594 }
595 }
596
597 return fmt.Errorf("fluent#write: failed to write after %d attempts", f.Config.MaxRetry)
598 }
599
600 func (f *Fluent) syncWriteMessage(ctx context.Context, msg *msgToSend) error {
601 f.muconn.Lock()
602 defer f.muconn.Unlock()
603
604 // Check if context is cancelled. If it is, we can return early here.
605 if err := ctx.Err(); err != nil {
606 return errIsClosing
607 }
608
609 if f.conn == nil {
610 return fmt.Errorf("fluent#write: connection has been closed before writing to it")
611 }
612
613 t := f.Config.WriteTimeout
614 var err error
615 if time.Duration(0) < t {
616 err = f.conn.SetWriteDeadline(time.Now().Add(t))
617 } else {
618 err = f.conn.SetWriteDeadline(time.Time{})
619 }
620
621 if err != nil {
622 return fmt.Errorf("fluent#write: failed to set write deadline: %w", err)
623 }
624 _, err = f.conn.Write(msg.data)
625 return err
626 }
627
628 func (f *Fluent) syncReadAck(ctx context.Context) (*AckResp, error) {
629 f.muconn.Lock()
630 defer f.muconn.Unlock()
631
632 resp := &AckResp{}
633 var err error
634
635 if f.conn == nil {
636 return resp, fmt.Errorf("fluent#read: connection has been closed before reading from it")
637 }
638
639 // Check if context is cancelled. If it is, we can return early here.
640 if err := ctx.Err(); err != nil {
641 return resp, errIsClosing
642 }
643
644 t := f.Config.ReadTimeout
645 if time.Duration(0) < t {
646 err = f.conn.SetReadDeadline(time.Now().Add(t))
647 } else {
648 err = f.conn.SetReadDeadline(time.Time{})
649 }
650 if err != nil {
651 return resp, fmt.Errorf("fluent#read: failed to set read deadline: %w", err)
652 }
653
654 if f.Config.MarshalAsJSON {
655 dec := json.NewDecoder(f.conn)
656 err = dec.Decode(resp)
657 } else {
658 r := msgp.NewReader(f.conn)
659 err = resp.DecodeMsg(r)
660 }
661
662 return resp, err
663 }
664
665 // write writes the provided msg to fluentd server. Its first return values is
666 // a bool indicating whether the write should be retried.
667 // This method relies on function literals to execute muconn.Unlock or
668 // muconn.RUnlock in deferred calls to ensure the mutex is unlocked even in
669 // the case of panic recovering.
670 func (f *Fluent) write(ctx context.Context, msg *msgToSend) (bool, error) {
671 if err := f.syncConnectWithRetry(ctx); err != nil {
672 // Here, we don't want to retry the write since connectWithRetry already
673 // retries Config.MaxRetry times to connect.
674 return false, fmt.Errorf("fluent#write: %w", err)
675 }
676
677 if err := f.syncWriteMessage(ctx, msg); err != nil {
678 f.syncClose(false)
679 return true, fmt.Errorf("fluent#write: %w", err)
680 }
681
682 // Acknowledgment check
683 if msg.ack != "" {
684 resp, err := f.syncReadAck(ctx)
685 if err != nil {
686 fmt.Fprintf(os.Stderr, "fluent#write: error reading message response ack %v. Closing connection...", err)
687 f.syncClose(false)
688 return true, err
689 }
690 if resp.Ack != msg.ack {
691 fmt.Fprintf(os.Stderr, "fluent#write: message ack (%s) doesn't match expected one (%s). Closing connection...", resp.Ack, msg.ack)
692 f.syncClose(false)
693 return true, err
694 }
695 }
696
697 return false, nil
698 }