-
Notifications
You must be signed in to change notification settings - Fork 0
/
fluentd.go
324 lines (282 loc) · 8.27 KB
/
fluentd.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
// Package fluentd provides the log driver for forwarding server logs
// to fluentd endpoints.
package fluentd // import "github.com/docker/docker/daemon/logger/fluentd"
import (
"context"
"math"
"net/url"
"strconv"
"strings"
"time"
"github.com/containerd/log"
"github.com/docker/docker/daemon/logger"
"github.com/docker/docker/daemon/logger/loggerutils"
"github.com/docker/docker/errdefs"
units "github.com/docker/go-units"
"github.com/fluent/fluent-logger-golang/fluent"
"github.com/pkg/errors"
)
type fluentd struct {
tag string
containerID string
containerName string
writer *fluent.Fluent
extra map[string]string
}
type location struct {
protocol string
host string
port int
path string
}
const (
name = "fluentd"
defaultBufferLimit = 1024 * 1024
defaultHost = "127.0.0.1"
defaultPort = 24224
defaultProtocol = "tcp"
// logger tries to reconnect 2**32 - 1 times
// failed (and panic) after 204 years [ 1.5 ** (2**32 - 1) - 1 seconds]
defaultMaxRetries = math.MaxInt32
defaultRetryWait = 1000
minReconnectInterval = 100 * time.Millisecond
maxReconnectInterval = 10 * time.Second
addressKey = "fluentd-address"
asyncKey = "fluentd-async"
asyncConnectKey = "fluentd-async-connect" // deprecated option (use fluent-async instead)
asyncReconnectIntervalKey = "fluentd-async-reconnect-interval"
bufferLimitKey = "fluentd-buffer-limit"
maxRetriesKey = "fluentd-max-retries"
requestAckKey = "fluentd-request-ack"
retryWaitKey = "fluentd-retry-wait"
subSecondPrecisionKey = "fluentd-sub-second-precision"
)
func init() {
if err := logger.RegisterLogDriver(name, New); err != nil {
panic(err)
}
if err := logger.RegisterLogOptValidator(name, ValidateLogOpt); err != nil {
panic(err)
}
}
// New creates a fluentd logger using the configuration passed in on
// the context. The supported context configuration variable is
// fluentd-address.
func New(info logger.Info) (logger.Logger, error) {
fluentConfig, err := parseConfig(info.Config)
if err != nil {
return nil, errdefs.InvalidParameter(err)
}
tag, err := loggerutils.ParseLogTag(info, loggerutils.DefaultTemplate)
if err != nil {
return nil, errdefs.InvalidParameter(err)
}
extra, err := info.ExtraAttributes(nil)
if err != nil {
return nil, errdefs.InvalidParameter(err)
}
log.G(context.TODO()).WithField("container", info.ContainerID).WithField("config", fluentConfig).
Debug("logging driver fluentd configured")
log, err := fluent.New(fluentConfig)
if err != nil {
return nil, err
}
return &fluentd{
tag: tag,
containerID: info.ContainerID,
containerName: info.ContainerName,
writer: log,
extra: extra,
}, nil
}
func (f *fluentd) Log(msg *logger.Message) error {
data := map[string]string{
"container_id": f.containerID,
"container_name": f.containerName,
"source": msg.Source,
"log": string(msg.Line),
}
for k, v := range f.extra {
data[k] = v
}
if msg.PLogMetaData != nil {
data["partial_message"] = "true"
data["partial_id"] = msg.PLogMetaData.ID
data["partial_ordinal"] = strconv.Itoa(msg.PLogMetaData.Ordinal)
data["partial_last"] = strconv.FormatBool(msg.PLogMetaData.Last)
}
ts := msg.Timestamp
logger.PutMessage(msg)
// fluent-logger-golang buffers logs from failures and disconnections,
// and these are transferred again automatically.
return f.writer.PostWithTime(f.tag, ts, data)
}
func (f *fluentd) Close() error {
return f.writer.Close()
}
func (f *fluentd) Name() string {
return name
}
// ValidateLogOpt looks for fluentd specific log option fluentd-address.
func ValidateLogOpt(cfg map[string]string) error {
for key := range cfg {
switch key {
case "env":
case "env-regex":
case "labels":
case "labels-regex":
case "tag":
case addressKey:
case asyncKey:
case asyncConnectKey:
case asyncReconnectIntervalKey:
case bufferLimitKey:
case maxRetriesKey:
case requestAckKey:
case retryWaitKey:
case subSecondPrecisionKey:
// Accepted
default:
return errors.Errorf("unknown log opt '%s' for fluentd log driver", key)
}
}
_, err := parseConfig(cfg)
return err
}
func parseConfig(cfg map[string]string) (fluent.Config, error) {
var config fluent.Config
loc, err := parseAddress(cfg[addressKey])
if err != nil {
return config, errors.Wrapf(err, "invalid fluentd-address (%s)", cfg[addressKey])
}
bufferLimit := defaultBufferLimit
if cfg[bufferLimitKey] != "" {
bl64, err := units.RAMInBytes(cfg[bufferLimitKey])
if err != nil {
return config, err
}
bufferLimit = int(bl64)
}
retryWait := defaultRetryWait
if cfg[retryWaitKey] != "" {
rwd, err := time.ParseDuration(cfg[retryWaitKey])
if err != nil {
return config, err
}
retryWait = int(rwd.Seconds() * 1000)
}
maxRetries := defaultMaxRetries
if cfg[maxRetriesKey] != "" {
mr64, err := strconv.ParseUint(cfg[maxRetriesKey], 10, strconv.IntSize)
if err != nil {
return config, err
}
maxRetries = int(mr64)
}
if cfg[asyncKey] != "" && cfg[asyncConnectKey] != "" {
return config, errors.Errorf("conflicting options: cannot specify both '%s' and '%s", asyncKey, asyncConnectKey)
}
async := false
if cfg[asyncKey] != "" {
if async, err = strconv.ParseBool(cfg[asyncKey]); err != nil {
return config, err
}
}
// TODO fluentd-async-connect is deprecated in driver v1.4.0. Remove after two stable releases
asyncConnect := false
if cfg[asyncConnectKey] != "" {
if asyncConnect, err = strconv.ParseBool(cfg[asyncConnectKey]); err != nil {
return config, err
}
}
asyncReconnectInterval := 0
if cfg[asyncReconnectIntervalKey] != "" {
interval, err := time.ParseDuration(cfg[asyncReconnectIntervalKey])
if err != nil {
return config, errors.Wrapf(err, "invalid value for %s", asyncReconnectIntervalKey)
}
if interval != 0 && (interval < minReconnectInterval || interval > maxReconnectInterval) {
return config, errors.Errorf("invalid value for %s: value (%q) must be between %s and %s",
asyncReconnectIntervalKey, interval, minReconnectInterval, maxReconnectInterval)
}
asyncReconnectInterval = int(interval.Milliseconds())
}
subSecondPrecision := false
if cfg[subSecondPrecisionKey] != "" {
if subSecondPrecision, err = strconv.ParseBool(cfg[subSecondPrecisionKey]); err != nil {
return config, err
}
}
requestAck := false
if cfg[requestAckKey] != "" {
if requestAck, err = strconv.ParseBool(cfg[requestAckKey]); err != nil {
return config, err
}
}
config = fluent.Config{
FluentPort: loc.port,
FluentHost: loc.host,
FluentNetwork: loc.protocol,
FluentSocketPath: loc.path,
BufferLimit: bufferLimit,
RetryWait: retryWait,
MaxRetry: maxRetries,
Async: async,
AsyncConnect: asyncConnect,
AsyncReconnectInterval: asyncReconnectInterval,
SubSecondPrecision: subSecondPrecision,
RequestAck: requestAck,
ForceStopAsyncSend: async || asyncConnect,
}
return config, nil
}
func parseAddress(address string) (*location, error) {
if address == "" {
return &location{
protocol: defaultProtocol,
host: defaultHost,
port: defaultPort,
path: "",
}, nil
}
if !strings.Contains(address, "://") {
address = defaultProtocol + "://" + address
}
addr, err := url.Parse(address)
if err != nil {
return nil, err
}
switch addr.Scheme {
case "unix":
if strings.TrimLeft(addr.Path, "/") == "" {
return nil, errors.New("path is empty")
}
return &location{protocol: addr.Scheme, path: addr.Path}, nil
case "tcp", "tls":
// continue processing below
default:
return nil, errors.Errorf("unsupported scheme: '%s'", addr.Scheme)
}
if addr.Path != "" {
return nil, errors.New("should not contain a path element")
}
host := defaultHost
port := defaultPort
if h := addr.Hostname(); h != "" {
host = h
}
if p := addr.Port(); p != "" {
// Port numbers are 16 bit: https://www.ietf.org/rfc/rfc793.html#section-3.1
portNum, err := strconv.ParseUint(p, 10, 16)
if err != nil {
return nil, errors.Wrap(err, "invalid port")
}
port = int(portNum)
}
return &location{
protocol: addr.Scheme,
host: host,
port: port,
path: "",
}, nil
}