Debian Codegraph @

fluent/fluent.go

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