-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathmain.go
323 lines (274 loc) · 7.7 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
package main
import (
"context"
"fmt"
stdlog "log"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
"time"
"github.com/bketelsen/logr"
"github.com/codegangsta/cli"
"github.com/corvus-ch/rabbitmq-cli-consumer/acknowledger"
"github.com/corvus-ch/rabbitmq-cli-consumer/collector"
"github.com/corvus-ch/rabbitmq-cli-consumer/command"
"github.com/corvus-ch/rabbitmq-cli-consumer/config"
"github.com/corvus-ch/rabbitmq-cli-consumer/consumer"
"github.com/corvus-ch/rabbitmq-cli-consumer/log"
"github.com/corvus-ch/rabbitmq-cli-consumer/processor"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/streadway/amqp"
)
var (
version = "dev"
commit = "none"
date = "unknown"
)
// flags is the list of global flags known to the application.
var flags []cli.Flag = []cli.Flag{
cli.StringFlag{
Name: "url, u",
Usage: "Connect with RabbitMQ using `URL`",
EnvVar: "AMQP_URL",
},
cli.StringFlag{
Name: "executable, e",
Usage: "Location of executable",
},
cli.StringFlag{
Name: "configuration, c",
Usage: "Location of configuration file",
},
cli.BoolFlag{
Name: "output, o",
Usage: "Enable logging of output from executable",
},
cli.BoolFlag{
Name: "verbose, V",
Usage: "Enable verbose mode (logs to stdout and stderr)",
},
cli.BoolFlag{
Name: "pipe, p",
Usage: "Pipe the message via STDIN instead of passing it as an argument. The message metadata will be passed as JSON via fd3.",
},
cli.BoolFlag{
Name: "include, i",
Usage: "Include metadata. Passes message as JSON data including headers, properties and message body. This flag will be ignored when `-pipe` is used.",
},
cli.BoolFlag{
Name: "strict-exit-code",
Usage: "Strict exit code processing will rise a fatal error if exit code is different from allowed onces.",
},
cli.StringFlag{
Name: "queue-name, q",
Usage: "Optional queue name to which can be passed in, without needing to define it in config, if set will override config queue name",
},
cli.BoolFlag{
Name: "no-datetime",
Usage: "prevents the output of date and time in the logs.",
},
cli.BoolFlag{
Name: "no-declare",
Usage: "prevents the queue from being declared.",
},
cli.BoolFlag{
Name: "metrics, m",
Usage: "enables metric to be exposed.",
},
cli.StringFlag{
Name: "web.listen-address",
Usage: "Address on which to expose metrics and web interface.",
Value: ":9566",
},
cli.StringFlag{
Name: "web.telemetry-path",
Usage: "Path under which to expose metrics.",
Value: "/metrics",
},
}
var ll logr.Logger
func main() {
NewApp().Run(os.Args)
}
// NewApp creates a new application instance with just one single action.
func NewApp() *cli.App {
app := cli.NewApp()
app.Name = "rabbitmq-cli-consumer"
app.Usage = "Consume RabbitMQ easily to any cli program"
app.Authors = []cli.Author{
{"Richard van den Brand", "[email protected]"},
{"Christian Häusler", "[email protected]"},
}
app.Version = fmt.Sprintf("%v, commit %v, built at %v", version, commit, date)
app.Flags = flags
app.Action = Action
app.ExitErrHandler = ExitErrHandler
return app
}
// Action is the function being run when the application gets executed.
func Action(c *cli.Context) error {
cfg, err := LoadConfiguration(c)
if err != nil {
return err
}
l, infW, errW, err := log.NewFromConfig(cfg)
if err != nil {
return err
}
ll = l
b := CreateBuilder(c.Bool("pipe"), cfg.RabbitMq.Compression, c.Bool("include"))
builder, err := command.NewBuilder(b, c.String("executable"), c.Bool("output"), l, infW, errW)
if err != nil {
return fmt.Errorf("failed to create command builder: %v", err)
}
ack := acknowledger.NewFromConfig(cfg)
p := processor.New(builder, ack, l)
client, err := consumer.NewFromConfig(cfg, p, l)
if err != nil {
return err
}
defer client.Close()
errs := make(chan error)
if c.Bool("metrics") {
ll.Infof("Registering metrics server at %v", c.String("web.listen-address"))
go func() {
errs <- setupAndServeMetrics(c.String("web.listen-address"), c.String("web.telemetry-path"))
}()
} else {
ll.Infof("Metrics disabled.")
}
go func() {
errs <- consume(client, l)
}()
return <-errs
}
func setupAndServeMetrics(addr string, path string) error {
srv := &http.Server{
Addr: addr,
// Good practice to set timeouts to avoid Slowloris attacks.
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
}
prometheus.MustRegister(collector.ProcessCounter)
prometheus.MustRegister(collector.ProcessDuration)
prometheus.MustRegister(collector.MessageDuration)
http.Handle(path, promhttp.Handler())
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`<html>
<head><title>rabbitmq-cli-consumer</title></head>
<body>
<h1>rabbitmq-cli-consumer</h1>
<p><a href='` + path + `'>Metrics</a></p>
</body>
</html>`))
})
if err := srv.ListenAndServe(); err != nil {
return errors.Wrap(err, "failed to serve metrics")
}
return nil
}
func consume(client *consumer.Consumer, l logr.Logger) error {
done := make(chan error)
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGTERM)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() {
done <- client.Consume(ctx)
}()
select {
case <-sig:
l.Info("Cancel consumption of messages.")
cancel()
return checkConsumeError(<-done)
case err := <-done:
return checkConsumeError(err)
}
}
func checkConsumeError(err error) error {
switch err.(type) {
case *amqp.Error:
if strings.Contains(err.Error(), "Exception (320) Reason:") {
return cli.NewExitError(fmt.Sprintf("connection closed: %v", err.(*amqp.Error).Reason), 10)
}
return err
case *processor.AcknowledgmentError:
return cli.NewExitError(err, 11)
default:
return err
}
}
// ExitErrHandler is a global error handler registered with the application.
func ExitErrHandler(_ *cli.Context, err error) {
if err == nil {
return
}
code := 1
if err.Error() != "" {
if ll != nil {
ll.Error(err)
} else {
stdlog.Printf("%+v\n", err)
}
}
if exitErr, ok := err.(cli.ExitCoder); ok {
code = exitErr.ExitCode()
}
os.Exit(code)
}
// CreateBuilder creates a new empty instance of command.Builder.
// The result must be passed to command.NewBuilder before it is ready to be used.
// If pipe is set to true, compression and metadata are ignored.
func CreateBuilder(pipe, compression, metadata bool) command.Builder {
if pipe {
return &command.PipeBuilder{}
}
return &command.ArgumentBuilder{
Compressed: compression,
WithMetadata: metadata,
}
}
// LoadConfiguration checks the configuration flags, loads the config from file and updates the config according the flags.
func LoadConfiguration(c *cli.Context) (*config.Config, error) {
file := c.String("configuration")
url := c.String("url")
queue := c.String("queue-name")
if file == "" && url == "" && queue == "" && c.String("executable") == "" {
cli.ShowAppHelp(c)
return nil, cli.NewExitError("", 1)
}
cfg, err := configuration(file)
if err != nil {
return nil, fmt.Errorf("failed parsing configuration: %s", err)
}
if len(url) > 0 {
cfg.RabbitMq.AmqpUrl = url
}
if queue != "" {
cfg.RabbitMq.Queue = queue
}
if c.IsSet("no-datetime") {
cfg.Logs.NoDateTime = c.Bool("no-datetime")
}
if c.IsSet("verbose") {
cfg.Logs.Verbose = c.Bool("verbose")
}
if c.IsSet("strict-exit-code") {
cfg.RabbitMq.Stricfailure = c.Bool("strict-exit-code")
}
if c.IsSet("no-declare") {
cfg.QueueSettings.Nodeclare = c.Bool("no-declare")
}
return cfg, nil
}
func configuration(file string) (*config.Config, error) {
if file == "" {
return config.CreateFromString("")
}
return config.LoadAndParse(file)
}