github.com/zhouyu0/docker-note@v0.0.0-20190722021225-b8d3825084db/daemon/logger/fluentd/fluentd.go (about)

     1  // Package fluentd provides the log driver for forwarding server logs
     2  // to fluentd endpoints.
     3  package fluentd // import "github.com/docker/docker/daemon/logger/fluentd"
     4  
     5  import (
     6  	"fmt"
     7  	"math"
     8  	"net"
     9  	"net/url"
    10  	"strconv"
    11  	"strings"
    12  	"time"
    13  
    14  	"github.com/docker/docker/daemon/logger"
    15  	"github.com/docker/docker/daemon/logger/loggerutils"
    16  	"github.com/docker/docker/pkg/urlutil"
    17  	"github.com/docker/go-units"
    18  	"github.com/fluent/fluent-logger-golang/fluent"
    19  	"github.com/pkg/errors"
    20  	"github.com/sirupsen/logrus"
    21  )
    22  
    23  type fluentd struct {
    24  	tag           string
    25  	containerID   string
    26  	containerName string
    27  	writer        *fluent.Fluent
    28  	extra         map[string]string
    29  }
    30  
    31  type location struct {
    32  	protocol string
    33  	host     string
    34  	port     int
    35  	path     string
    36  }
    37  
    38  const (
    39  	name = "fluentd"
    40  
    41  	defaultProtocol    = "tcp"
    42  	defaultHost        = "127.0.0.1"
    43  	defaultPort        = 24224
    44  	defaultBufferLimit = 1024 * 1024
    45  
    46  	// logger tries to reconnect 2**32 - 1 times
    47  	// failed (and panic) after 204 years [ 1.5 ** (2**32 - 1) - 1 seconds]
    48  	defaultRetryWait  = 1000
    49  	defaultMaxRetries = math.MaxInt32
    50  
    51  	addressKey            = "fluentd-address"
    52  	bufferLimitKey        = "fluentd-buffer-limit"
    53  	retryWaitKey          = "fluentd-retry-wait"
    54  	maxRetriesKey         = "fluentd-max-retries"
    55  	asyncConnectKey       = "fluentd-async-connect"
    56  	subSecondPrecisionKey = "fluentd-sub-second-precision"
    57  )
    58  
    59  func init() {
    60  	if err := logger.RegisterLogDriver(name, New); err != nil {
    61  		logrus.Fatal(err)
    62  	}
    63  	if err := logger.RegisterLogOptValidator(name, ValidateLogOpt); err != nil {
    64  		logrus.Fatal(err)
    65  	}
    66  }
    67  
    68  // New creates a fluentd logger using the configuration passed in on
    69  // the context. The supported context configuration variable is
    70  // fluentd-address.
    71  func New(info logger.Info) (logger.Logger, error) {
    72  	loc, err := parseAddress(info.Config[addressKey])
    73  	if err != nil {
    74  		return nil, err
    75  	}
    76  
    77  	tag, err := loggerutils.ParseLogTag(info, loggerutils.DefaultTemplate)
    78  	if err != nil {
    79  		return nil, err
    80  	}
    81  
    82  	extra, err := info.ExtraAttributes(nil)
    83  	if err != nil {
    84  		return nil, err
    85  	}
    86  
    87  	bufferLimit := defaultBufferLimit
    88  	if info.Config[bufferLimitKey] != "" {
    89  		bl64, err := units.RAMInBytes(info.Config[bufferLimitKey])
    90  		if err != nil {
    91  			return nil, err
    92  		}
    93  		bufferLimit = int(bl64)
    94  	}
    95  
    96  	retryWait := defaultRetryWait
    97  	if info.Config[retryWaitKey] != "" {
    98  		rwd, err := time.ParseDuration(info.Config[retryWaitKey])
    99  		if err != nil {
   100  			return nil, err
   101  		}
   102  		retryWait = int(rwd.Seconds() * 1000)
   103  	}
   104  
   105  	maxRetries := defaultMaxRetries
   106  	if info.Config[maxRetriesKey] != "" {
   107  		mr64, err := strconv.ParseUint(info.Config[maxRetriesKey], 10, strconv.IntSize)
   108  		if err != nil {
   109  			return nil, err
   110  		}
   111  		maxRetries = int(mr64)
   112  	}
   113  
   114  	asyncConnect := false
   115  	if info.Config[asyncConnectKey] != "" {
   116  		if asyncConnect, err = strconv.ParseBool(info.Config[asyncConnectKey]); err != nil {
   117  			return nil, err
   118  		}
   119  	}
   120  
   121  	subSecondPrecision := false
   122  	if info.Config[subSecondPrecisionKey] != "" {
   123  		if subSecondPrecision, err = strconv.ParseBool(info.Config[subSecondPrecisionKey]); err != nil {
   124  			return nil, err
   125  		}
   126  	}
   127  
   128  	fluentConfig := fluent.Config{
   129  		FluentPort:         loc.port,
   130  		FluentHost:         loc.host,
   131  		FluentNetwork:      loc.protocol,
   132  		FluentSocketPath:   loc.path,
   133  		BufferLimit:        bufferLimit,
   134  		RetryWait:          retryWait,
   135  		MaxRetry:           maxRetries,
   136  		AsyncConnect:       asyncConnect,
   137  		SubSecondPrecision: subSecondPrecision,
   138  	}
   139  
   140  	logrus.WithField("container", info.ContainerID).WithField("config", fluentConfig).
   141  		Debug("logging driver fluentd configured")
   142  
   143  	log, err := fluent.New(fluentConfig)
   144  	if err != nil {
   145  		return nil, err
   146  	}
   147  	return &fluentd{
   148  		tag:           tag,
   149  		containerID:   info.ContainerID,
   150  		containerName: info.ContainerName,
   151  		writer:        log,
   152  		extra:         extra,
   153  	}, nil
   154  }
   155  
   156  func (f *fluentd) Log(msg *logger.Message) error {
   157  	data := map[string]string{
   158  		"container_id":   f.containerID,
   159  		"container_name": f.containerName,
   160  		"source":         msg.Source,
   161  		"log":            string(msg.Line),
   162  	}
   163  	for k, v := range f.extra {
   164  		data[k] = v
   165  	}
   166  	if msg.PLogMetaData != nil {
   167  		data["partial_message"] = "true"
   168  	}
   169  
   170  	ts := msg.Timestamp
   171  	logger.PutMessage(msg)
   172  	// fluent-logger-golang buffers logs from failures and disconnections,
   173  	// and these are transferred again automatically.
   174  	return f.writer.PostWithTime(f.tag, ts, data)
   175  }
   176  
   177  func (f *fluentd) Close() error {
   178  	return f.writer.Close()
   179  }
   180  
   181  func (f *fluentd) Name() string {
   182  	return name
   183  }
   184  
   185  // ValidateLogOpt looks for fluentd specific log option fluentd-address.
   186  func ValidateLogOpt(cfg map[string]string) error {
   187  	for key := range cfg {
   188  		switch key {
   189  		case "env":
   190  		case "env-regex":
   191  		case "labels":
   192  		case "tag":
   193  		case addressKey:
   194  		case bufferLimitKey:
   195  		case retryWaitKey:
   196  		case maxRetriesKey:
   197  		case asyncConnectKey:
   198  		case subSecondPrecisionKey:
   199  			// Accepted
   200  		default:
   201  			return fmt.Errorf("unknown log opt '%s' for fluentd log driver", key)
   202  		}
   203  	}
   204  
   205  	_, err := parseAddress(cfg[addressKey])
   206  	return err
   207  }
   208  
   209  func parseAddress(address string) (*location, error) {
   210  	if address == "" {
   211  		return &location{
   212  			protocol: defaultProtocol,
   213  			host:     defaultHost,
   214  			port:     defaultPort,
   215  			path:     "",
   216  		}, nil
   217  	}
   218  
   219  	protocol := defaultProtocol
   220  	givenAddress := address
   221  	if urlutil.IsTransportURL(address) {
   222  		url, err := url.Parse(address)
   223  		if err != nil {
   224  			return nil, errors.Wrapf(err, "invalid fluentd-address %s", givenAddress)
   225  		}
   226  		// unix and unixgram socket
   227  		if url.Scheme == "unix" || url.Scheme == "unixgram" {
   228  			return &location{
   229  				protocol: url.Scheme,
   230  				host:     "",
   231  				port:     0,
   232  				path:     url.Path,
   233  			}, nil
   234  		}
   235  		// tcp|udp
   236  		protocol = url.Scheme
   237  		address = url.Host
   238  	}
   239  
   240  	host, port, err := net.SplitHostPort(address)
   241  	if err != nil {
   242  		if !strings.Contains(err.Error(), "missing port in address") {
   243  			return nil, errors.Wrapf(err, "invalid fluentd-address %s", givenAddress)
   244  		}
   245  		return &location{
   246  			protocol: protocol,
   247  			host:     host,
   248  			port:     defaultPort,
   249  			path:     "",
   250  		}, nil
   251  	}
   252  
   253  	portnum, err := strconv.Atoi(port)
   254  	if err != nil {
   255  		return nil, errors.Wrapf(err, "invalid fluentd-address %s", givenAddress)
   256  	}
   257  	return &location{
   258  		protocol: protocol,
   259  		host:     host,
   260  		port:     portnum,
   261  		path:     "",
   262  	}, nil
   263  }