forked from fluent/fluentd-forwarder
/
main.go
371 lines (348 loc) · 9.89 KB
/
main.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package main
import (
gcfg "code.google.com/p/gcfg"
"crypto/x509"
"flag"
"fmt"
strftime "github.com/jehiah/go-strftime"
ioextras "github.com/moriyoshi/go-ioextras"
logging "github.com/op/go-logging"
fluentd_forwarder "github.com/fluent/fluentd-forwarder"
"io"
"io/ioutil"
"log"
"net/url"
"os"
"path/filepath"
"reflect"
"runtime/pprof"
"strings"
"time"
)
type FluentdForwarderParams struct {
RetryInterval time.Duration
ConnectionTimeout time.Duration
WriteTimeout time.Duration
FlushInterval time.Duration
Parallelism int
JournalGroupPath string
MaxJournalChunkSize int64
ListenOn string
OutputType string
ForwardTo string
LogLevel logging.Level
LogFile string
DatabaseName string
TableName string
ApiKey string
Ssl bool
SslCACertBundleFile string
CPUProfileFile string
}
type PortWorker interface {
fluentd_forwarder.Port
fluentd_forwarder.Worker
}
var progName = os.Args[0]
var progVersion string
func MustParseDuration(s string) time.Duration {
d, err := time.ParseDuration(s)
if err != nil {
panic(err)
}
return d
}
func Error(fmtStr string, args ...interface{}) {
fmt.Fprint(os.Stderr, progName, ": ")
fmt.Fprintf(os.Stderr, fmtStr, args...)
fmt.Fprint(os.Stderr, "\n")
}
type LogLevelValue logging.Level
func (v *LogLevelValue) String() string {
return logging.Level(*v).String()
}
func (v *LogLevelValue) Set(s string) error {
_v, err := logging.LogLevel(s)
*v = LogLevelValue(_v)
return err
}
func updateFlagsByConfig(configFile string, flagSet *flag.FlagSet) error {
config := struct {
Fluentd_Forwarder struct {
Retry_interval string `retry-interval`
Conn_timeout string `conn-timeout`
Write_timeout string `write-timeout`
Flush_interval string `flush-interval`
Listen_on string `listen-on`
To string `to`
Buffer_path string `buffer-path`
Buffer_chunk_limit string `buffer-chunk-limit`
Log_level string `log-level`
Ca_certs string `ca-certs`
Cpuprofile string `cpuprofile`
Log_file string `log-file`
}
}{}
err := gcfg.ReadFileInto(&config, configFile)
if err != nil {
return err
}
r := reflect.ValueOf(config.Fluentd_Forwarder)
rt := r.Type()
for i, l := 0, rt.NumField(); i < l; i += 1 {
f := rt.Field(i)
fv := r.Field(i)
v := fv.String()
if v != "" {
err := flagSet.Set(string(f.Tag), v)
if err != nil {
return err
}
}
}
return nil
}
func ParseArgs() *FluentdForwarderParams {
configFile := ""
retryInterval := (time.Duration)(0)
connectionTimeout := (time.Duration)(0)
writeTimeout := (time.Duration)(0)
flushInterval := (time.Duration)(0)
parallelism := 0
listenOn := ""
forwardTo := ""
journalGroupPath := ""
maxJournalChunkSize := int64(16777216)
logLevel := LogLevelValue(logging.INFO)
sslCACertBundleFile := ""
cpuProfileFile := ""
logFile := ""
flagSet := flag.NewFlagSet(progName, flag.ExitOnError)
flagSet.StringVar(&configFile, "config", "", "configuration file")
flagSet.DurationVar(&retryInterval, "retry-interval", 0, "retry interval in which connection is tried against the remote agent")
flagSet.DurationVar(&connectionTimeout, "conn-timeout", MustParseDuration("10s"), "connection timeout")
flagSet.DurationVar(&writeTimeout, "write-timeout", MustParseDuration("10s"), "write timeout on wire")
flagSet.DurationVar(&flushInterval, "flush-interval", MustParseDuration("5s"), "flush interval in which the events are forwareded to the remote agent")
flagSet.IntVar(¶llelism, "parallelism", 1, "Number of chunks to submit at once (for td output)")
flagSet.StringVar(&listenOn, "listen-on", "127.0.0.1:24224", "interface address and port on which the forwarder listens")
flagSet.StringVar(&forwardTo, "to", "fluent://127.0.0.1:24225", "host and port to which the events are forwarded")
flagSet.StringVar(&journalGroupPath, "buffer-path", "*", "directory / path on which buffer files are created. * may be used within the path to indicate the prefix or suffix like var/pre*suf")
flagSet.Int64Var(&maxJournalChunkSize, "buffer-chunk-limit", 16777216, "Maximum size of a buffer chunk")
flagSet.Var(&logLevel, "log-level", "log level (defaults to INFO)")
flagSet.StringVar(&sslCACertBundleFile, "ca-certs", "", "path to SSL CA certificate bundle file")
flagSet.StringVar(&cpuProfileFile, "cpuprofile", "", "write CPU profile to file")
flagSet.StringVar(&logFile, "log-file", "", "path of the log file. log will be written to stderr if unspecified")
flagSet.Parse(os.Args[1:])
if configFile != "" {
err := updateFlagsByConfig(configFile, flagSet)
if err != nil {
Error("%s", err.Error())
os.Exit(1)
}
}
ssl := false
outputType := ""
databaseName := "*"
tableName := "*"
apiKey := ""
if strings.Contains(forwardTo, "//") {
u, err := url.Parse(forwardTo)
if err != nil {
Error("%s", err.Error())
os.Exit(1)
}
switch u.Scheme {
case "fluent", "fluentd":
outputType = "fluent"
forwardTo = u.Host
case "td+http", "td+https":
outputType = "td"
forwardTo = u.Host
if u.User != nil {
apiKey = u.User.Username()
}
if u.Scheme == "td+https" {
ssl = true
}
p := strings.Split(u.Path, "/")
if len(p) > 1 {
databaseName = p[1]
}
if len(p) > 2 {
tableName = p[2]
}
}
} else {
outputType = "fluent"
}
if outputType == "" {
Error("Invalid output specifier")
os.Exit(1)
} else if outputType == "fluent" {
if !strings.ContainsRune(forwardTo, ':') {
forwardTo += ":24224"
}
}
return &FluentdForwarderParams{
RetryInterval: retryInterval,
ConnectionTimeout: connectionTimeout,
WriteTimeout: writeTimeout,
FlushInterval: flushInterval,
Parallelism: parallelism,
ListenOn: listenOn,
OutputType: outputType,
ForwardTo: forwardTo,
Ssl: ssl,
DatabaseName: databaseName,
TableName: tableName,
ApiKey: apiKey,
JournalGroupPath: journalGroupPath,
MaxJournalChunkSize: maxJournalChunkSize,
LogLevel: logging.Level(logLevel),
LogFile: logFile,
SslCACertBundleFile: sslCACertBundleFile,
CPUProfileFile: cpuProfileFile,
}
}
func ValidateParams(params *FluentdForwarderParams) bool {
if params.RetryInterval < 0 {
Error("Retry interval may not be negative")
return false
}
if params.RetryInterval > 0 && params.RetryInterval < 100000000 {
Error("Retry interval must be greater than or equal to 100ms")
return false
}
if params.FlushInterval < 100000000 {
Error("Flush interval must be greater than or equal to 100ms")
return false
}
if params.FlushInterval < 100000000 {
Error("Flush interval must be greater than or equal to 100ms")
return false
}
switch params.OutputType {
case "fluent":
if params.RetryInterval == 0 {
params.RetryInterval = MustParseDuration("5s")
}
if params.RetryInterval > params.FlushInterval {
Error("Retry interval may not be greater than flush interval")
return false
}
case "td":
if params.RetryInterval != 0 {
Error("Retry interval will be ignored")
return false
}
}
return true
}
func main() {
params := ParseArgs()
if !ValidateParams(params) {
os.Exit(1)
}
logWriter := (io.Writer)(nil)
if params.LogFile != "" {
logWriter = ioextras.NewStaticRotatingWriter(
func(_ interface{}) (string, error) {
path := strftime.Format(params.LogFile, time.Now())
return path, nil
},
func(path string, _ interface{}) (io.Writer, error) {
dir, _ := filepath.Split(path)
err := os.MkdirAll(dir, os.FileMode(0777))
if err != nil {
return nil, err
}
return os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.FileMode(0666))
},
nil,
)
} else {
logWriter = os.Stderr
}
logBackend := logging.NewLogBackend(logWriter, "[fluentd-forwarder] ", log.Ldate|log.Ltime|log.Lmicroseconds)
logging.SetBackend(logBackend)
logger := logging.MustGetLogger("fluentd-forwarder")
logging.SetLevel(params.LogLevel, "fluentd-forwarder")
if progVersion != "" {
logger.Info("Version %s starting...", progVersion)
}
workerSet := fluentd_forwarder.NewWorkerSet()
if params.CPUProfileFile != "" {
f, err := os.Create(params.CPUProfileFile)
if err != nil {
Error(err.Error())
os.Exit(1)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
output := (PortWorker)(nil)
err := (error)(nil)
switch params.OutputType {
case "fluent":
output, err = fluentd_forwarder.NewForwardOutput(
logger,
params.ForwardTo,
params.RetryInterval,
params.ConnectionTimeout,
params.WriteTimeout,
params.FlushInterval,
params.JournalGroupPath,
params.MaxJournalChunkSize,
)
case "td":
rootCAs := (*x509.CertPool)(nil)
if params.SslCACertBundleFile != "" {
b, err := ioutil.ReadFile(params.SslCACertBundleFile)
if err != nil {
Error("Failed to read CA bundle file: %s", err.Error())
os.Exit(1)
}
rootCAs = x509.NewCertPool()
if !rootCAs.AppendCertsFromPEM(b) {
Error("No valid certificate found in %s", params.SslCACertBundleFile)
os.Exit(1)
}
}
output, err = fluentd_forwarder.NewTDOutput(
logger,
params.ForwardTo,
params.ConnectionTimeout,
params.WriteTimeout,
params.FlushInterval,
params.Parallelism,
params.JournalGroupPath,
params.MaxJournalChunkSize,
params.ApiKey,
params.DatabaseName,
params.TableName,
"",
params.Ssl,
rootCAs,
"", // TODO:http-proxy
)
}
if err != nil {
Error("%s", err.Error())
return
}
workerSet.Add(output)
input, err := fluentd_forwarder.NewForwardInput(logger, params.ListenOn, output)
if err != nil {
Error(err.Error())
return
}
workerSet.Add(input)
signalHandler := NewSignalHandler(workerSet)
input.Start()
output.Start()
signalHandler.Start()
for _, worker := range workerSet.Slice() {
worker.WaitForShutdown()
}
logger.Notice("Shutting down...")
}