-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
398 lines (332 loc) · 10.8 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
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/giant-stone/go/glogging"
"github.com/giant-stone/go/gutil"
"github.com/giant-stone/gmq/gmq"
)
var (
cmdAddMsg bool
cmdGetMsg bool
cmdListMsg bool
cmdListFailed bool
cmdDelMsg bool
cmdDelQueue bool
cmdListQueue bool
cmdCleanQueue bool
cmdPauseq string
cmdResumeq string
cmdPrintStats bool
ago int64
dsnRedis string
msgId string
payloadStr string
queueName string
state string
optLimit int64
optOffset int64
optByForce bool
loglevel string
useUTC bool
)
var (
msgStatList = []string{
gmq.MsgStatePending,
gmq.MsgStateProcessing,
gmq.MsgStateFailed,
}
)
var (
buildTs = ""
showBuildTs bool
)
var (
buildDsn = ""
)
const (
DefaultDSN = "redis://127.0.0.1:6379/0"
)
func main() {
flag.StringVar(&loglevel, "l", "debug", "loglevel debug,info,warn,error")
flag.StringVar(&dsnRedis, "d", "", "redis DSN")
// commands
flag.BoolVar(&cmdPrintStats, "stat", false, "print queue stats")
flag.BoolVar(&cmdAddMsg, "add", false, "append a message into queue")
flag.BoolVar(&cmdGetMsg, "get", false, "get a message detail")
flag.BoolVar(&cmdListMsg, "list", false, "list messages from a queue ")
flag.BoolVar(&cmdListFailed, "listfailed", false, "list history records of the failed message")
flag.BoolVar(&cmdDelMsg, "del", false, "delete a message from queue")
flag.BoolVar(&cmdListQueue, "listqueue", false, "list all queue names")
flag.BoolVar(&cmdDelQueue, "delqueue", false, "delete a message from queue")
flag.BoolVar(&cmdCleanQueue, "cleanqueue", false, "delete expired message(s) from queue")
flag.StringVar(&cmdPauseq, "pause", "", "queuename to pause")
flag.StringVar(&cmdResumeq, "resume", "", "queuename to resume")
// options
flag.BoolVar(&optByForce, "f", false, "delete old message matched id(fulluri) before append")
flag.StringVar(&queueName, "q", gmq.DefaultQueueName, "queue name")
flag.StringVar(&payloadStr, "p", "", "message payload in JSON")
flag.StringVar(&msgId, "i", "", "message id, it is auto-generated by default")
stateList := strings.Join(msgStatList, ",")
flag.StringVar(&state, "s", "failed", fmt.Sprintf("must be one of %s, required for -list, queue state to search", stateList))
flag.Int64Var(&ago, "ago", gmq.TTLMsg, "delete expired message(s) how long ago, in seconds")
flag.Int64Var(&optLimit, "n", gmq.DefaultMaxItemsLimit, fmt.Sprintf("use with -list, maximum number of messages to display, default is %d", gmq.DefaultMaxItemsLimit))
flag.Int64Var(&optOffset, "o", 0, "use with -list, first messages offset to display, start with 0")
flag.BoolVar(&useUTC, "u", false, "process time in UTC instead of local")
flag.BoolVar(&showBuildTs, "v", false, "show build timestamp")
flag.Parse()
flag.Usage = mdbcliUsage
glogging.Init([]string{"stdout"}, glogging.Loglevel(loglevel))
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
if !cmdPrintStats &&
!cmdAddMsg && !cmdGetMsg && !cmdListMsg && !cmdListFailed && !cmdDelMsg &&
!cmdDelQueue && !cmdListQueue && !cmdCleanQueue &&
cmdPauseq != "" && cmdResumeq != "" &&
!showBuildTs {
flag.Usage()
os.Exit(1)
}
if showBuildTs {
fmt.Println(buildTs)
os.Exit(0)
}
if dsnRedis == "" {
dsnRedis = buildDsn
}
if dsnRedis == "" {
dsnRedis = DefaultDSN
}
broker, err := gmq.NewBrokerRedis(dsnRedis)
broker.UTC(useUTC)
gutil.ExitOnErr(err)
ctx := context.Background()
if cmdPauseq != "" {
pauseQueue(ctx, broker, cmdPauseq)
os.Exit(0)
} else if cmdResumeq != "" {
resumeQueue(ctx, broker, cmdResumeq)
os.Exit(0)
}
if cmdPrintStats {
printStats(ctx, broker)
} else if cmdAddMsg {
addMsg(ctx, broker, queueName, payloadStr, msgId, optByForce)
} else if cmdGetMsg {
getMsg(ctx, broker, queueName, msgId)
} else if cmdListMsg {
if state == "" {
flag.Usage()
os.Exit(1)
}
listMsg(ctx, broker, queueName, optLimit, optOffset)
} else if cmdListFailed {
listFailed(ctx, broker, queueName, msgId, optLimit, optOffset)
} else if cmdDelMsg {
delMsg(ctx, broker, queueName, msgId)
} else if cmdListQueue {
listQueue(ctx, broker)
} else if cmdDelQueue {
delQueue(ctx, broker, queueName)
} else if cmdCleanQueue {
cleanQueue(ctx, broker, queueName, ago)
} else {
flag.Usage()
os.Exit(1)
}
fmt.Print("\n")
}
func cleanQueue(ctx context.Context, broker gmq.Broker, queueName string, ago int64) {
cutoff := time.Second * time.Duration(ago)
err := broker.DeleteAgo(ctx, queueName, cutoff)
gutil.ExitOnErr(err)
}
func listQueue(ctx context.Context, broker gmq.Broker) {
names, err := broker.ListQueue(ctx)
gutil.ExitOnErr(err)
for _, name := range names {
fmt.Println(name)
}
}
func listFailed(ctx context.Context, broker gmq.Broker, queueName, msgId string, limit, offset int64) {
if msgId == "" {
fmt.Println("the option -i / message id is required")
os.Exit(1)
}
msgs, err := broker.ListFailed(ctx, queueName, msgId, limit, offset)
gutil.ExitOnErr(err)
if len(msgs) == 0 {
fmt.Printf("history of failed message matched queue=%s id=%s not found \n", queueName, msgId)
os.Exit(0)
}
for _, msg := range msgs {
printMsg(msg)
}
}
func pauseQueue(ctx context.Context, broker gmq.Broker, queuename string) {
if err := broker.Pause(ctx, queuename); err != nil {
fmt.Printf("Pausing queue %s failed. errer(%s) \n", queuename, err.Error())
} else {
fmt.Printf("Pause queue %s \n", queuename)
}
}
func resumeQueue(ctx context.Context, broker gmq.Broker, queuename string) {
if err := broker.Resume(ctx, queuename); err != nil {
fmt.Printf("Resuming queue %s failed. errer(%s) \n", cmdPauseq, err.Error())
} else {
fmt.Printf("Resume queue %s \n", queuename)
}
}
func addMsg(ctx context.Context, broker gmq.Broker, queueName, payloadStr, id string, byForce bool) {
if payloadStr == "" && id == "" {
fmt.Println("payload or id is required")
return
}
if optByForce {
gutil.CheckErr(broker.DeleteMsg(ctx, queueName, id))
}
rs, err := broker.Enqueue(ctx, &gmq.Msg{
Payload: []byte(payloadStr),
Id: id,
}, gmq.OptQueueName(queueName))
gutil.ExitOnErr(err)
dat, _ := json.Marshal(rs)
fmt.Println("reply", string(dat))
}
func printStats(ctx context.Context, broker gmq.Broker) {
queues, err := broker.GetStats(ctx)
gutil.ExitOnErr(err)
fmt.Print("\n# gmq Statistic \n\n")
fmt.Print("## Daily Statistic \n\n")
if len(queues) == 0 {
fmt.Println("Related info not found. Do consumer(s) have not start yet?")
} else {
listQueueNames := make([]string, 0)
for _, rsStat := range queues {
fmt.Printf("queue=%s total=%d pending=%d processing=%d failed=%d \n",
rsStat.Name,
rsStat.Total,
rsStat.Pending,
rsStat.Processing,
rsStat.Failed,
)
listQueueNames = append(listQueueNames, rsStat.Name)
}
printStatsWeekly(ctx, broker, listQueueNames)
}
}
func printStatsWeekly(ctx context.Context, broker gmq.Broker, listQueueNames []string) {
rsStat, err := broker.GetStatsWeekly(ctx, listQueueNames)
gutil.ExitOnErr(err)
now := time.Now()
if useUTC {
now = now.UTC()
} else {
now = now.Local()
}
fmt.Printf("\n## Weekly Statistic: %s ~ %s \n\n", now.AddDate(0, 0, -7).Format("2006-01-02"), now.Format("2006-01-02"))
totalCompleted := int64(0)
totalFailed := int64(0)
for _, item := range rsStat {
totalCompleted += item.Completed
totalFailed += item.Failed
fmt.Printf("date=%s completed=%d, failed=%d, total=%d \n", item.Date, item.Completed, item.Failed, item.Completed+item.Failed)
}
fmt.Printf("\ncompleted=%d, failed=%d, total=%d \n", totalCompleted, totalFailed, totalCompleted+totalFailed)
}
func getMsg(ctx context.Context, broker gmq.Broker, queueName, msgId string) {
msg, err := broker.GetMsg(ctx, queueName, msgId)
if err != nil {
if err == gmq.ErrNoMsg {
fmt.Printf("message matched queue=%s id=%s not found", queueName, msgId)
return
}
gutil.ExitOnErr(err)
}
printMsg(msg)
}
func printMsg(msg *gmq.Msg) {
fmt.Println("\nRAW\n", msg)
dat, err := json.MarshalIndent(msg, "", " ")
gutil.ExitOnErr(err)
fmt.Println("INTERNAL\n", string(dat))
if msg.Created > 0 {
t := time.UnixMilli(msg.Created)
if useUTC {
t = t.UTC()
} else {
t = t.Local()
}
fmt.Printf(" Created=%d (%s) \n", msg.Created, t.Format(time.RFC3339))
}
if msg.Updated > 0 {
t := time.UnixMilli(msg.Updated)
if useUTC {
t = t.UTC()
} else {
t = t.Local()
}
fmt.Printf(" Updated=%d (%s) \n", msg.Updated, t.Format(time.RFC3339))
}
if msg.Expireat > 0 {
t := time.UnixMilli(msg.Expireat)
if useUTC {
t = t.UTC()
} else {
t = t.Local()
}
fmt.Printf(" Expiredat=%d (%s) \n", msg.Expireat, t.Format(time.RFC3339))
}
}
func listMsg(ctx context.Context, broker gmq.Broker, queueName string, limit, offset int64) {
msgs, err := broker.ListMsg(ctx, queueName, state, limit, offset)
if err != nil {
if err == gmq.ErrNoMsg {
fmt.Printf("message matched queue=%s state=%s not found", queueName, state)
return
}
gutil.ExitOnErr(err)
}
fmt.Printf("list messages of queue=%s state=%s \n\n", queueName, state)
for _, msg := range msgs {
fmt.Println(msg)
}
}
func delMsg(ctx context.Context, broker gmq.Broker, queueName, msgId string) {
err := broker.DeleteMsg(ctx, queueName, msgId)
if err != nil {
if err != gmq.ErrNoMsg {
gutil.ExitOnErr(err)
}
}
fmt.Printf("queue=%s msgId=%s deleted \n", queueName, msgId)
}
func delQueue(ctx context.Context, broker gmq.Broker, queueName string) {
err := broker.DeleteQueue(ctx, queueName)
if err != nil {
if err != gmq.ErrNoMsg {
gutil.ExitOnErr(err)
}
}
fmt.Printf("queue %s cleared", queueName)
}
func mdbcliUsage() {
fmt.Printf("\nmdbcli is a terminal supports gmq queue management \n\n")
fmt.Printf("Usage: %s <one of following>", os.Args[0])
fmt.Printf(" -stat print snapshots of all queues and statistics for the last 8 days\n\n")
fmt.Printf(" -list list all or part of messages of a queue \n\n\t -list -q <queueName> -s <failed|pending|processing> [-n n] [-o m]\n\n")
fmt.Printf(" -listfailed list history records of the failed messages \n\n\t -listfailed -q <queueName> -i <msgId> [-n n] [-o m]\n\n")
fmt.Printf(" -get print detail of certain message by offering its queue and id \n\n\t -get -i <msgId> -q <queueName> \n\n")
fmt.Printf(" -add add certain message by offering its queue, id and payload \n\n\t -add -i <msgId> -q <queueName> -p <payload> \n\n")
fmt.Printf(" -del delete a certain message with by offering its queue and id \n\n\t -del -i <msgId> -q <queueName> \n\n")
fmt.Printf(" -delqueue delete queue \n\n\t -delqueue -q <queueName>\n\n")
fmt.Printf(" -cleanqueue delete expired message(s) \n\n\t -cleanqueue -q <queueName> -ago <ago in seconds> \n\n")
fmt.Printf(" -listqueue list all queue names \n\n")
fmt.Printf(" -pause pause queue consumption \n\n\t -pause -q <queueName>\n\n")
fmt.Printf(" -resume resume queue consumption \n\n\t -resume -q <queueName>\n\n")
}