forked from redpanda-data/connect
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
411 lines (361 loc) · 12.5 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
// Copyright (c) 2014 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"
"context"
"fmt"
_ "net/http/pprof"
"runtime/pprof"
"flag"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/Jeffail/benthos/lib/api"
"github.com/Jeffail/benthos/lib/buffer"
"github.com/Jeffail/benthos/lib/cache"
"github.com/Jeffail/benthos/lib/input"
"github.com/Jeffail/benthos/lib/manager"
"github.com/Jeffail/benthos/lib/output"
"github.com/Jeffail/benthos/lib/pipeline"
"github.com/Jeffail/benthos/lib/processor"
"github.com/Jeffail/benthos/lib/processor/condition"
"github.com/Jeffail/benthos/lib/types"
"github.com/Jeffail/benthos/lib/util"
"github.com/Jeffail/benthos/lib/util/service"
"github.com/Jeffail/benthos/lib/util/service/log"
"github.com/Jeffail/benthos/lib/util/service/metrics"
)
//------------------------------------------------------------------------------
// 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.LoggerConfig `json:"logger" yaml:"logger"`
Metrics metrics.Config `json:"metrics" yaml:"metrics"`
SystemCloseTimeoutMS int `json:"sys_exit_timeout_ms" yaml:"sys_exit_timeout_ms"`
}
// NewConfig returns a new configuration with default values.
func NewConfig() Config {
metricsConf := metrics.NewConfig()
metricsConf.Prefix = "benthos"
return Config{
HTTP: api.NewConfig(),
Input: input.NewConfig(),
Buffer: buffer.NewConfig(),
Pipeline: pipeline.NewConfig(),
Output: output.NewConfig(),
Manager: manager.NewConfig(),
Logger: log.NewLoggerConfig(),
Metrics: metricsConf,
SystemCloseTimeoutMS: 20000,
}
}
// 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() (interface{}, error) {
inConf, err := input.SanitiseConfig(c.Input)
if err != nil {
return nil, err
}
var pipeConf interface{}
pipeConf, err = pipeline.SanitiseConfig(c.Pipeline)
if err != nil {
return nil, err
}
var outConf interface{}
outConf, err = output.SanitiseConfig(c.Output)
if err != nil {
return nil, err
}
var bufConf interface{}
bufConf, err = buffer.SanitiseConfig(c.Buffer)
if err != nil {
return nil, err
}
var metConf interface{}
metConf, err = metrics.SanitiseConfig(c.Metrics)
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"`
SystemCloseTimeoutMS interface{} `json:"sys_exit_timeout_ms" yaml:"sys_exit_timeout_ms"`
}{
HTTP: c.HTTP,
Input: inConf,
Buffer: bufConf,
Pipeline: pipeConf,
Output: outConf,
Manager: c.Manager,
Logger: c.Logger,
Metrics: metConf,
SystemCloseTimeoutMS: c.SystemCloseTimeoutMS,
}, nil
}
//------------------------------------------------------------------------------
// Extra flags
var (
printInputs = flag.Bool(
"list-inputs", false,
"Print a list of available input options, then exit",
)
printOutputs = flag.Bool(
"list-outputs", false,
"Print a list of available output options, then exit",
)
printBuffers = flag.Bool(
"list-buffers", false,
"Print a list of available buffer options, then exit",
)
printProcessors = flag.Bool(
"list-processors", false,
"Print a list of available processor options, then exit",
)
printConditions = flag.Bool(
"list-conditions", false,
"Print a list of available processor condition options, then exit",
)
printCaches = flag.Bool(
"list-caches", false,
"Print a list of available cache options, then exit",
)
)
//------------------------------------------------------------------------------
// bootstrap reads cmd args and either parses and config file or prints helper
// text and exits.
func bootstrap() Config {
config := NewConfig()
// A list of default config paths to check for if not explicitly defined
defaultPaths := []string{
"/benthos.yaml",
"/etc/benthos/config.yaml",
"/etc/benthos.yaml",
}
// Override default help printing
flag.Usage = func() {
fmt.Fprintln(os.Stderr, "Usage: benthos [flags...]")
fmt.Fprintln(os.Stderr, "Flags:")
flag.PrintDefaults()
fmt.Fprintf(os.Stderr,
"\nFor example configs use --print-yaml or --print-json\n"+
"For a list of available inputs or outputs use --list-inputs or --list-outputs\n"+
"For a list of available buffer options use --list-buffers\n")
}
// Load configuration etc
if !service.Bootstrap(&config, defaultPaths...) {
os.Exit(0)
}
// If we only want to print our inputs or outputs we should exit afterwards
if *printInputs || *printOutputs || *printBuffers || *printProcessors || *printConditions || *printCaches {
if *printInputs {
fmt.Println(input.Descriptions())
}
if *printProcessors {
fmt.Println(processor.Descriptions())
}
if *printConditions {
fmt.Println(condition.Descriptions())
}
if *printBuffers {
fmt.Println(buffer.Descriptions())
}
if *printOutputs {
fmt.Println(output.Descriptions())
}
if *printCaches {
fmt.Println(cache.Descriptions())
}
os.Exit(1)
}
return config
}
// createPipeline creates a pipeline based on the supplied configuration file,
// and return a closable pool of pipeline objects, a channel indicating that all
// inputs and outputs have seized, or an error.
func createPipeline(
config Config, mgr types.Manager, logger log.Modular, stats metrics.Type,
) (*util.ClosablePool, *util.ClosablePool, chan struct{}, error) {
// Create two pools, this helps manage ordered closure of all pipeline
// components. We have a tiered (t1) and an non-tiered (t2) pool. If the
// tiered pool cannot close within our allotted time period then we try
// closing the second non-tiered pool. If the second pool also fails then we
// exit the service ungracefully.
poolt1, poolt2 := util.NewClosablePool(), util.NewClosablePool()
// Create our input pipe
inputPipe, err := input.New(config.Input, mgr, logger, stats)
if err != nil {
logger.Errorf("Input error (%s): %v\n", config.Input.Type, err)
return nil, nil, nil, err
}
poolt1.Add(1, inputPipe)
poolt2.Add(0, inputPipe)
// Create a buffer
buf, err := buffer.New(config.Buffer, logger, stats)
if err != nil {
logger.Errorf("Buffer error (%s): %v\n", config.Buffer.Type, err)
return nil, nil, nil, err
}
poolt1.Add(2, buf)
poolt2.Add(0, buf)
// Create pipeline pool
pipe, err := pipeline.New(config.Pipeline, mgr, logger, stats)
if err != nil {
logger.Errorf("Pipeline error: %v\n", err)
return nil, nil, nil, err
}
poolt1.Add(3, pipe)
poolt2.Add(0, pipe)
// Create our output pipe
outputPipe, err := output.New(config.Output, mgr, logger, stats)
if err != nil {
logger.Errorf("Output error (%s): %v\n", config.Output.Type, err)
return nil, nil, nil, err
}
poolt1.Add(10, outputPipe)
poolt2.Add(0, outputPipe)
outputPipe.StartReceiving(pipe.TransactionChan())
pipe.StartReceiving(buf.TransactionChan())
buf.StartReceiving(inputPipe.TransactionChan())
closeChan := make(chan struct{})
// If our outputs close down then we should shut down the service
go func() {
for {
if err := outputPipe.WaitForClose(time.Second * 60); err == nil {
closeChan <- struct{}{}
return
}
}
}()
return poolt1, poolt2, closeChan, nil
}
func main() {
// Bootstrap by reading cmd flags and configuration file.
config := bootstrap()
// Logging and stats aggregation.
var logger log.Modular
// Note: Only log to Stderr if one of our outputs is stdout.
if config.Output.Type == "stdout" {
logger = log.NewLogger(os.Stderr, config.Logger)
} else {
logger = log.NewLogger(os.Stdout, config.Logger)
}
logger.Infoln("Launching a benthos instance, use CTRL+C to close.")
// Create our metrics type.
stats, err := metrics.New(config.Metrics)
if err != nil {
logger.Errorf("Metrics error: %v\n", err)
os.Exit(1)
}
defer stats.Close()
// Create HTTP API with a sanitised service config.
sanConf, err := config.Sanitised()
if err != nil {
logger.Warnf("Failed to generate sanitised config: %v\n", err)
}
httpServer := api.New(service.Version, service.DateBuilt, config.HTTP, sanConf, logger, stats)
// Create resource manager.
manager, err := manager.New(config.Manager, httpServer, logger, stats)
if err != nil {
logger.Errorf("Failed to create resource: %v\n", err)
os.Exit(1)
}
// Create data pipelines.
poolTiered, poolNonTiered, outputsClosedChan, err := createPipeline(config, manager, logger, stats)
if err != nil {
logger.Errorf("Service closing due to: %v\n", err)
os.Exit(1)
}
// Start HTTP server.
httpServerClosedChan := make(chan struct{})
go func() {
logger.Infof(
"Listening for HTTP requests at: %v\n",
"http://"+config.HTTP.Address,
)
httpErr := httpServer.ListenAndServe()
if httpErr != nil && httpErr != http.ErrServerClosed {
logger.Errorf("HTTP Server error: %v\n", httpErr)
}
close(httpServerClosedChan)
}()
// Defer ordered pool clean up.
defer func() {
tout := time.Millisecond * time.Duration(config.SystemCloseTimeoutMS)
go func() {
httpServer.Shutdown(context.Background())
select {
case <-httpServerClosedChan:
case <-time.After(tout / 2):
logger.Warnln("Service failed to close HTTP server gracefully in time.")
}
}()
go func() {
<-time.After(tout + time.Second)
logger.Warnln(
"Service failed to close cleanly within allocated time." +
" Exiting forcefully and dumping stack trace to stderr.",
)
pprof.Lookup("goroutine").WriteTo(os.Stderr, 1)
os.Exit(1)
}()
if err := poolTiered.Close(tout / 2); err != nil {
logger.Warnln(
"Service failed to close using ordered tiers, you may receive a duplicate " +
"message on the next service start.",
)
if err = poolNonTiered.Close(tout / 2); err != nil {
logger.Warnln(
"Service failed to close cleanly within allocated time. Exiting forcefully.",
)
dumpBuf := bytes.NewBuffer(nil)
pprof.Lookup("goroutine").WriteTo(dumpBuf, 1)
logger.Debugln(dumpBuf.String())
os.Exit(1)
}
}
}()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
// Wait for termination signal
select {
case <-sigChan:
logger.Infoln("Received SIGTERM, the service is closing.")
case <-outputsClosedChan:
logger.Infoln("Pipeline has terminated. Shutting down the service.")
case <-httpServerClosedChan:
logger.Infoln("HTTP Server has terminated. Shutting down the service.")
}
}
//------------------------------------------------------------------------------