-
Notifications
You must be signed in to change notification settings - Fork 814
/
main.go
547 lines (478 loc) · 14.1 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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
// Copyright (c) 2018 Ashley Jeffs
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"path/filepath"
"sort"
"strings"
"github.com/Jeffail/benthos/lib/api"
"github.com/Jeffail/benthos/lib/buffer"
"github.com/Jeffail/benthos/lib/input"
"github.com/Jeffail/benthos/lib/log"
"github.com/Jeffail/benthos/lib/manager"
"github.com/Jeffail/benthos/lib/metrics"
"github.com/Jeffail/benthos/lib/output"
"github.com/Jeffail/benthos/lib/pipeline"
"github.com/Jeffail/benthos/lib/processor"
yaml "gopkg.in/yaml.v2"
)
//------------------------------------------------------------------------------
// Config is the benthos configuration struct.
type Config struct {
HTTP api.Config `json:"http" yaml:"http"`
Input input.Config `json:"input" yaml:"input"`
Buffer buffer.Config `json:"buffer" yaml:"buffer"`
Pipeline pipeline.Config `json:"pipeline" yaml:"pipeline"`
Output output.Config `json:"output" yaml:"output"`
Manager manager.Config `json:"resources" yaml:"resources"`
Logger log.Config `json:"logger" yaml:"logger"`
Metrics metrics.Config `json:"metrics" yaml:"metrics"`
}
// NewConfig returns a new configuration with default values.
func NewConfig() Config {
return Config{
HTTP: api.NewConfig(),
Input: input.NewConfig(),
Buffer: buffer.NewConfig(),
Pipeline: pipeline.NewConfig(),
Output: output.NewConfig(),
Manager: manager.NewConfig(),
Logger: log.NewConfig(),
Metrics: metrics.NewConfig(),
}
}
// Sanitised returns a sanitised copy of the Benthos configuration, meaning
// fields of no consequence (unused inputs, outputs, processors etc) are
// excluded.
func (c Config) Sanitised(sanitBuffer, sanitPipe bool) (interface{}, error) {
inConf, err := input.SanitiseConfig(c.Input)
if err != nil {
return nil, err
}
var bufConf interface{}
if sanitBuffer {
bufConf, err = buffer.SanitiseConfig(c.Buffer)
if err != nil {
return nil, err
}
} else {
bufConf = c.Buffer
}
var pipeConf interface{}
if sanitPipe {
pipeConf, err = pipeline.SanitiseConfig(c.Pipeline)
if err != nil {
return nil, err
}
} else {
pipeConf = c.Pipeline
}
var outConf interface{}
outConf, err = output.SanitiseConfig(c.Output)
if err != nil {
return nil, err
}
var mgrConf interface{}
mgrConf, err = manager.SanitiseConfig(c.Manager)
if err != nil {
return nil, err
}
return struct {
HTTP interface{} `json:"http" yaml:"http"`
Input interface{} `json:"input" yaml:"input"`
Buffer interface{} `json:"buffer" yaml:"buffer"`
Pipeline interface{} `json:"pipeline" yaml:"pipeline"`
Output interface{} `json:"output" yaml:"output"`
Manager interface{} `json:"resources" yaml:"resources"`
Logger interface{} `json:"logger" yaml:"logger"`
Metrics interface{} `json:"metrics" yaml:"metrics"`
}{
HTTP: c.HTTP,
Input: inConf,
Buffer: bufConf,
Pipeline: pipeConf,
Output: outConf,
Manager: mgrConf,
Logger: c.Logger,
Metrics: c.Metrics,
}, nil
}
//------------------------------------------------------------------------------
func create(t, path string, resBytes []byte) {
if err := ioutil.WriteFile(path, resBytes, 0644); err != nil {
panic(err)
}
fmt.Printf("Generated '%v' at: %v\n", t, path)
}
func createYAML(t, path string, sanit interface{}) {
resBytes := []byte("# This file was auto generated by benthos_config_gen.\n")
cBytes, err := yaml.Marshal(sanit)
if err != nil {
panic(err)
}
resBytes = append(resBytes, cBytes...)
if err = ioutil.WriteFile(path, resBytes, 0644); err != nil {
panic(err)
}
fmt.Printf("Generated '%v' config at: %v\n", t, path)
}
func createJSON(t, path string, sanit interface{}) {
resBytes, err := json.MarshalIndent(sanit, "", " ")
if err != nil {
panic(err)
}
if err = ioutil.WriteFile(path, resBytes, 0644); err != nil {
panic(err)
}
fmt.Printf("Generated '%v' config at: %v\n", t, path)
}
func envify(rootPath string, conf interface{}, paths map[string]string) (newConf interface{}) {
genBytes, err := json.Marshal(conf)
if err != nil {
panic(err)
}
dec := json.NewDecoder(bytes.NewReader(genBytes))
dec.UseNumber()
var genConf interface{}
if err = dec.Decode(&genConf); err != nil {
panic(err)
}
staticlist := []string{
"INPUT_TYPE",
"OUTPUT_TYPE",
}
blacklist := []string{
"READ_UNTIL",
"OUTPUT_BROKER_OUTPUTS_RETRY",
"CONDITIONAL",
"PROCESS_FIELD",
"PROCESS_MAP",
"FILTER",
"DEDUPE",
"INPUT_BROKER_INPUTS_BROKER",
"OUTPUT_BROKER_OUTPUTS_BROKER",
}
aliases := map[string]string{
"INPUT_BROKER_INPUTS": "INPUT",
"INPUT_BROKER_COPIES": "INPUTS",
"PIPELINE_PROCESSORS": "PROCESSOR",
"PIPELINE_THREADS": "PROCESSOR_THREADS",
"OUTPUT_BROKER_OUTPUTS": "OUTPUT",
"OUTPUT_BROKER_PATTERN": "OUTPUTS_PATTERN",
"OUTPUT_BROKER_COPIES": "OUTPUTS",
}
var traverse func(path string, to *interface{}, from interface{})
traverse = func(path string, to *interface{}, from interface{}) {
if obj, isObj := from.(map[string]interface{}); isObj {
newMap := map[string]interface{}{}
keyIter:
for k, v := range obj {
newPath := path + "_" + strings.Replace(strings.ToUpper(k), "-", "_", -1)
for _, b := range staticlist {
if strings.Contains(newPath, b) {
// Preserve values that hit our staticlist.
newMap[k] = v
continue keyIter
}
}
for _, b := range blacklist {
if strings.Contains(newPath, b) {
// Skip values that hit our blacklist.
continue keyIter
}
}
var newVal interface{}
traverse(newPath, &newVal, v)
if newVal != nil {
newMap[k] = newVal
}
}
if len(newMap) > 0 {
*to = newMap
}
return
} else if len(path) == 0 {
panic("Environment values at path root")
}
if array, isArray := from.([]interface{}); isArray {
var newArray []interface{}
for _, ele := range array {
var newVal interface{}
traverse(path, &newVal, ele)
if newVal != nil {
newArray = append(newArray, newVal)
}
}
if len(newArray) > 0 {
*to = newArray
}
return
}
for alias := range aliases {
if strings.Contains(path, alias) {
path = strings.Replace(path, alias, aliases[alias], 1)
}
}
var valStr string
switch t := from.(type) {
case string:
valStr = t
case bool:
if t {
valStr = "true"
} else {
valStr = "false"
}
case json.Number:
valStr = t.String()
}
paths[path] = valStr
if len(valStr) > 0 {
*to = "${" + path + ":" + valStr + "}"
} else {
*to = "${" + path + "}"
}
}
traverse(rootPath, &newConf, genConf)
return
}
func formatEnvVars(vars map[string]string) []byte {
categories := []string{
"HTTP", "INPUT", "BUFFER", "PROCESSOR", "OUTPUT", "LOGGER", "METRICS",
}
priorityVars := []string{
"INPUTS", "PROCESSOR_THREADS", "OUTPUTS", "OUTPUTS_PATTERN",
"INPUT_TYPE", "BUFFER_TYPE", "PROCESSOR_TYPE",
"OUTPUT_TYPE", "METRICS_TYPE",
}
sortedVars := []string{}
for k := range vars {
sortedVars = append(sortedVars, k)
}
sort.Strings(sortedVars)
var buf bytes.Buffer
buf.WriteString(`Environment Config
==================
This document was auto generated by ` + "`benthos_config_gen`" + `.
The environment variables config ` + "[`default.yaml`](default.yaml)" + ` is an
auto generated Benthos configuration where _all_ fields can be set with
environment variables. The architecture of the config is a standard bridge
between N replicated sources, M replicated sinks and an optional buffer and
processing pipeline between them.
The original intent of this config is to be deployed within a docker image, but
as it is a standard config it can be used in other deployments.
In order to use this config simply define your env vars and point Benthos to it.
For example, to send Kafka data to RabbitMQ you can run:
` + "``` sh" + `
INPUT_TYPE=kafka_balanced \
INPUT_KAFKA_ADDRESSES=localhost:9092 \
INPUT_KAFKA_TOPIC=foo-topic \
INPUT_KAFKA_CONSUMER_GROUP=foo-consumer \
OUTPUT_TYPE=amqp \
OUTPUT_AMQP_URL=amqp://guest:guest@localhost:5672/ \
OUTPUT_AMQP_EXCHANGE=foo-exchange \
OUTPUT_AMQP_EXCHANGE_TYPE=direct \
benthos -c ./config/env/default.yaml
` + "```" + `
All variables within the config are listed in this document.
## Contents
`)
for _, section := range categories {
buf.WriteByte('\n')
buf.WriteString("- [" + section + "](#" + strings.ToLower(section) + ")")
}
buf.WriteByte('\n')
for _, section := range categories {
buf.WriteString("\n")
buf.WriteString("## " + section)
buf.WriteString("\n\n```\n")
catVars := []string{}
for _, v := range priorityVars {
if !strings.HasPrefix(v, section) {
continue
}
catVars = append(catVars, v)
}
sortedIter:
for _, v := range sortedVars {
if !strings.HasPrefix(v, section) {
continue
}
for _, v2 := range priorityVars {
if v == v2 {
continue sortedIter
}
}
catVars = append(catVars, v)
}
vMaxLen := 0
for _, v := range catVars {
if len(v) > vMaxLen {
vMaxLen = len(v)
}
}
for _, v := range catVars {
buf.WriteString(v)
if defVal := vars[v]; len(defVal) > 0 {
for i := len(v); i < vMaxLen; i++ {
buf.WriteByte(' ')
}
buf.WriteString(" = " + defVal)
}
buf.WriteByte('\n')
}
buf.WriteString("```\n")
}
return buf.Bytes()
}
func createEnvConf(configsDir string) {
inConf := input.NewConfig()
inConf.Type = "dynamic"
inBrokerConf := struct {
Copies int `json:"copies"`
Inputs []interface{} `json:"inputs"`
}{
Copies: 1,
Inputs: []interface{}{inConf},
}
procConf := processor.NewConfig()
procConf.Type = "noop"
pipeConf := pipeline.NewConfig()
pipeConf.Processors = append(pipeConf.Processors, procConf)
outConf := output.NewConfig()
outConf.Type = "dynamic"
outBrokerConf := struct {
Copies int `json:"copies"`
Pattern string `json:"pattern"`
Outputs []interface{} `json:"outputs"`
}{
Copies: 1,
Pattern: "greedy",
Outputs: []interface{}{outConf},
}
conf := NewConfig()
envConf := struct {
HTTP interface{} `json:"http"`
Input interface{} `json:"input"`
Buffer interface{} `json:"buffer"`
Pipeline interface{} `json:"pipeline"`
Output interface{} `json:"output"`
Logger interface{} `json:"logger"`
Metrics interface{} `json:"metrics"`
}{
HTTP: conf.HTTP,
Input: struct {
Type string `json:"type"`
Broker interface{} `json:"broker"`
}{
Type: "broker",
Broker: inBrokerConf,
},
Buffer: conf.Buffer,
Pipeline: pipeConf,
Output: struct {
Type string `json:"type"`
Broker interface{} `json:"broker"`
}{
Type: "broker",
Broker: outBrokerConf,
},
Logger: log.NewConfig(),
Metrics: metrics.NewConfig(),
}
pathsMap := map[string]string{}
envConf.HTTP = envify("HTTP", envConf.HTTP, pathsMap)
envConf.Input = envify("INPUT", envConf.Input, pathsMap)
envConf.Buffer = envify("BUFFER", envConf.Buffer, pathsMap)
envConf.Pipeline = envify("PIPELINE", envConf.Pipeline, pathsMap)
envConf.Output = envify("OUTPUT", envConf.Output, pathsMap)
envConf.Logger = envify("LOGGER", envConf.Logger, pathsMap)
envConf.Metrics = envify("METRICS", envConf.Metrics, pathsMap)
createYAML("environment file", filepath.Join(configsDir, "env", "default.yaml"), envConf)
create("environment file docs", filepath.Join(configsDir, "env", "README.md"), formatEnvVars(pathsMap))
}
func main() {
configsDir := "./config"
flag.StringVar(&configsDir, "dir", configsDir, "The directory to write config examples")
flag.Parse()
// Get list of all types (both input and output).
typeMap := map[string]struct{}{}
for t := range input.Constructors {
typeMap[t] = struct{}{}
}
for t := range output.Constructors {
typeMap[t] = struct{}{}
}
// Generate configs for all types.
for t := range typeMap {
conf := NewConfig()
conf.Input.Processors = nil
conf.Output.Processors = nil
conf.Pipeline.Processors = nil
if _, exists := input.Constructors[t]; exists {
conf.Input.Type = t
}
if _, exists := output.Constructors[t]; exists {
conf.Output.Type = t
}
sanit, err := conf.Sanitised(true, true)
if err != nil {
panic(err)
}
createYAML(t, filepath.Join(configsDir, t+".yaml"), sanit)
createJSON(t, filepath.Join(configsDir, t+".json"), sanit)
}
// Create processor configs for all types.
for t := range processor.Constructors {
conf := NewConfig()
conf.Input.Processors = nil
conf.Output.Processors = nil
procConf := processor.NewConfig()
procConf.Type = t
conf.Pipeline.Processors = append(conf.Pipeline.Processors, procConf)
sanit, err := conf.Sanitised(true, true)
if err != nil {
panic(err)
}
createYAML(t, filepath.Join(configsDir, "processors", t+".yaml"), sanit)
createJSON(t, filepath.Join(configsDir, "processors", t+".json"), sanit)
}
// Create buffers config
{
t := "buffers"
conf := NewConfig()
conf.Input.Processors = nil
conf.Output.Processors = nil
sanit, err := conf.Sanitised(false, true)
if err != nil {
panic(err)
}
createYAML(t, filepath.Join(configsDir, t+".yaml"), sanit)
createJSON(t, filepath.Join(configsDir, t+".json"), sanit)
}
// Create Environment Vars Config
createEnvConf(configsDir)
}
//------------------------------------------------------------------------------