-
Notifications
You must be signed in to change notification settings - Fork 1
/
coyote.go
315 lines (291 loc) Β· 8.58 KB
/
coyote.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
package main
import (
"context"
"crypto/tls"
"database/sql"
"fmt"
"log"
"net/url"
"os"
"os/signal"
"strings"
"github.com/fatih/color"
"github.com/google/uuid"
"github.com/manifoldco/promptui"
amqp "github.com/rabbitmq/amqp091-go"
"github.com/urfave/cli/v2"
_ "modernc.org/sqlite"
)
var Version = "development"
const usage = `coyote [global options]
Examples:
coyote --url amqps://user@myurl --exchange myexchange --store events.sqlite
coyote --url amqps://user:password@myurl --noprompt --exchange myexchange --store events.sqlite
coyote --url amqps://user:password@myurl --noprompt --insecure --exchange myexchange
Exchange binding formats:
--exchange myexchange # All messages in single exchange
--exchange myexchange1=mykey1 # Messages with routing key in a single exchange
--exchange myexchange1=mykey1,myexchange1=mykey2 # Messages with routing keys in a single exchange
--exchange myexchange1,myexchange2 # All messages in multiple exchanges
--exchange myexchange1=mykey1,myexchange2=mykey2 # Messages with routing keys in multiple exchanges
--exchange myexchange1,myexchange2=mykey2 # Messages with or without routing keys in multiple exchanges`
type listen struct {
c []combination
}
type combination struct {
exchange string
routingKey string
}
func (l *listen) Set(value string) (err error) {
for _, comb := range strings.Split(value, ",") {
pair := strings.Split(comb, "=")
length := len(pair)
if length == 1 {
if len(pair[0]) < 1 {
return fmt.Errorf("exchange name can not be empty")
}
l.c = append(l.c, combination{exchange: pair[0], routingKey: "#"})
} else if length == 2 {
if len(pair[0]) < 1 {
return fmt.Errorf("exchange name can not be empty")
}
if len(pair[1]) < 1 {
return fmt.Errorf("routing key can not be empty when '=' is provided")
}
l.c = append(l.c, combination{exchange: pair[0], routingKey: pair[1]})
} else {
return fmt.Errorf("valid values are ['a=x' 'a,b' 'a=x,b=y' 'a,b=y'] where a and b are exchanges, x and y are routing keys")
}
}
return nil
}
func (l *listen) String() string {
return ""
}
func main() {
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt)
defer func() {
signal.Stop(signalChan)
cancel()
}()
go func() {
select {
case <-signalChan:
cancel()
case <-ctx.Done():
}
<-signalChan
os.Exit(2)
}()
app := &cli.App{
Name: "coyote",
Usage: "Coyote is a RabbitMQ message sink.",
Version: Version,
UsageText: usage,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "url",
Required: true,
Usage: "RabbitMQ url, must start with amqps:// or amqp://.",
},
&cli.GenericFlag{
Name: "exchange",
Required: true,
Value: &listen{},
Usage: "Exchange & routing key combinations to listen messages.",
},
&cli.StringFlag{
Name: "queue",
Usage: "Interceptor queue name. If provided, interceptor queue will not be auto deleted.",
},
&cli.StringFlag{
Name: "store",
Usage: "SQLite filename to store events.",
},
&cli.BoolFlag{
Name: "insecure",
Usage: "Skips certificate verification.",
},
&cli.BoolFlag{
Name: "noprompt",
Usage: "Disables password prompt.",
},
&cli.BoolFlag{
Name: "silent",
Usage: "Disables terminal print.",
},
},
Action: func(ctx *cli.Context) error {
u, err := url.Parse(ctx.String("url"))
if err != nil {
return fmt.Errorf("%s %w", color.RedString("failed to parse provided url:"), err)
}
if !ctx.Bool("noprompt") {
prompt := promptui.Prompt{
Label: "Password",
Mask: '*',
}
password, err := prompt.Run()
if err != nil {
return fmt.Errorf("%s %w", color.RedString("failed to provide password:"), err)
}
u.User = url.UserPassword(u.User.String(), password)
}
conn, err := amqp.DialTLS(u.String(), &tls.Config{InsecureSkipVerify: ctx.Bool("insecure")})
if err != nil {
return fmt.Errorf("%s %w", color.RedString("failed to connect to RabbitMQ:"), err)
}
defer func() {
err := conn.Close()
if err != nil {
log.Fatal(err)
}
log.Printf("π Terminating AMQP connection")
}()
ch, err := conn.Channel()
if err != nil {
return fmt.Errorf("%s %w", color.RedString("failed to open a channel:"), err)
}
defer func() {
err := ch.Close()
if err != nil {
log.Fatal(err)
}
log.Printf("π Terminating AMQP channel")
}()
var queueName string
persistent := ctx.IsSet("queue")
if persistent {
queueName = ctx.String("queue")
} else {
queueName = fmt.Sprintf("%s.%s", "coyote", uuid.NewString())
}
q, err := ch.QueueDeclare(
queueName, // queue name
false, // is durable
!persistent, // is auto delete
!persistent, // is exclusive
false, // is no wait
nil, // args
)
if err != nil {
return fmt.Errorf("%s %w", color.RedString("failed to declare a queue:"), err)
}
for _, c := range ctx.Generic("exchange").(*listen).c {
err = ch.ExchangeDeclarePassive(
c.exchange, // exchange name
"topic", // exchange kind
true, // is durable
false, // is auto delete
false, // is internal
false, // is no wait
nil, // args
)
if err != nil {
return fmt.Errorf("%s %w", color.RedString("failed to connect to exchange:"), err)
}
err = ch.QueueBind(
q.Name, // interceptor queue name
c.routingKey, // routing key to bind
c.exchange, // exchange to listen
false, // is no wait
nil, // args
)
if err != nil {
return fmt.Errorf("%s %w", color.RedString("failed to bind to queue:"), err)
} else {
log.Printf("π Listening from exchange %s with routing key %s", color.YellowString(c.exchange), color.YellowString(c.routingKey))
}
}
deliveries, err := ch.Consume(
q.Name, // queue name to consume from
"", // consumer tag
true, // is auto ack
false, // is exclusive
false, // is no local
false, // is no wait
nil, // args
)
if err != nil {
return fmt.Errorf("%s %w", color.RedString("failed to register a consumer:"), err)
}
go func() {
var db *sql.DB
var insert *sql.Stmt
if ctx.IsSet("store") {
filename := ctx.String("store")
db, err = sql.Open("sqlite", filename+"?_txlock=exclusive&mode=rwc")
if err != nil {
log.Fatal(err)
}
defer func() {
err := db.Close()
if err != nil {
log.Fatal(err)
}
log.Printf("π Closing database connection")
}()
create, err := db.Prepare(`CREATE TABLE IF NOT EXISTS event
(
"id" INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
"timestamp" TIMESTAMP DEFAULT (DATETIME(CURRENT_TIMESTAMP, 'localtime')),
"exchange" TEXT,
"routing_key" TEXT,
"correlation_id" TEXT,
"reply_to" TEXT,
"headers" TEXT,
"body" TEXT
);`)
if err != nil {
log.Fatal(err)
}
if _, err := create.Exec(); err != nil {
log.Fatal(err)
}
insert, err = db.Prepare(`INSERT INTO event(exchange, routing_key, correlation_id, reply_to, headers, body)
VALUES (?, ?, ?, ?, ?, ?)`)
if err != nil {
log.Fatal(err)
}
}
count := 0
for d := range deliveries {
if insert != nil {
if _, err := insert.Exec(d.Exchange, d.RoutingKey, d.CorrelationId, d.ReplyTo, fmt.Sprint(d.Headers), string(d.Body)); err != nil {
log.Fatal(err)
}
}
if !ctx.Bool("silent") {
log.Printf("π§ %s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s\n%s%s",
color.YellowString("Received a message"),
color.GreenString("# Exchange : "),
d.Exchange,
color.GreenString("# Routing-key : "),
d.RoutingKey,
color.GreenString("# Correlation-id : "),
d.CorrelationId,
color.GreenString("# Reply-to : "),
d.ReplyTo,
color.GreenString("# Headers : "),
d.Headers,
color.GreenString("# Body : "),
d.Body)
} else {
count++
fmt.Printf("\033[1A\033[K")
log.Printf("πΎ Consumed %s messages. To exit press %s", color.GreenString("%d", count), color.YellowString("CTRL+C"))
}
}
}()
log.Printf("β³ Waiting for messages. To exit press %s", color.YellowString("CTRL+C"))
<-ctx.Done()
return nil
},
}
if err := app.RunContext(ctx, os.Args); err != nil {
log.Fatal(err)
}
}