forked from mercury2269/sqsmover
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
216 lines (167 loc) · 5.84 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
package main
import (
"fmt"
"strconv"
"github.com/apex/log"
"github.com/apex/log/handlers/cli"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/fatih/color"
"github.com/tj/go-progress"
"github.com/tj/go/term"
"gopkg.in/alecthomas/kingpin.v2"
)
var (
sourceQueue = kingpin.Flag("source", "Source queue to move messages from").Short('s').Required().String()
destinationQueue = kingpin.Flag("destination", "Destination queue to move messages to").Short('d').Required().String()
region = kingpin.Flag("region", "AWS Region for source and destination queues").Short('r').Default("us-west-2").String()
)
func main() {
log.SetHandler(cli.Default)
fmt.Println()
defer fmt.Println()
kingpin.UsageTemplate(kingpin.CompactUsageTemplate)
kingpin.Parse()
sess, err := session.NewSessionWithOptions(
session.Options{
Config: aws.Config{Region: aws.String(*region)},
SharedConfigState: session.SharedConfigEnable,
},
)
if err != nil {
log.Error(color.New(color.FgRed).Sprintf("Unable to create AWS session for region \r\n", *region))
return
}
svc := sqs.New(sess)
err, sourceQueueUrl := resolveQueueUrl(svc, *sourceQueue)
if err != nil {
logAwsError("Failed to resolve source queue", err)
return
}
log.Info(color.New(color.FgCyan).Sprintf("Source queue url: %s", sourceQueueUrl))
err, destinationQueueUrl := resolveQueueUrl(svc, *destinationQueue)
if err != nil {
logAwsError("Failed to resolve destination queue", err)
return
}
log.Info(color.New(color.FgCyan).Sprintf("Destination queue url: %s", destinationQueueUrl))
queueAttributes, err := svc.GetQueueAttributes(&sqs.GetQueueAttributesInput{
QueueUrl: aws.String(sourceQueueUrl),
AttributeNames: []*string{aws.String("All")},
})
numberOfMessages, _ := strconv.Atoi(*queueAttributes.Attributes["ApproximateNumberOfMessages"])
log.Info(color.New(color.FgCyan).Sprintf("Approximate number of messages in the source queue: %s",
*queueAttributes.Attributes["ApproximateNumberOfMessages"]))
if numberOfMessages == 0 {
log.Info("Looks like nothing to move. Done.")
return
}
moveMessages(sourceQueueUrl, destinationQueueUrl, svc, numberOfMessages)
}
func resolveQueueUrl(svc *sqs.SQS, queueName string) (error, string) {
params := &sqs.GetQueueUrlInput{
QueueName: aws.String(queueName),
}
resp, err := svc.GetQueueUrl(params)
if err != nil {
return err, ""
}
return nil, *resp.QueueUrl
}
func logAwsError(message string, err error) {
if awsErr, ok := err.(awserr.Error); ok {
log.Error(color.New(color.FgRed).Sprintf("%s. Error: %s", message, awsErr.Message()))
} else {
log.Error(color.New(color.FgRed).Sprintf("%s. Error: %s", message, err.Error()))
}
}
func convertToEntries(messages []*sqs.Message) []*sqs.SendMessageBatchRequestEntry {
result := make([]*sqs.SendMessageBatchRequestEntry, len(messages))
for i, message := range messages {
result[i] = &sqs.SendMessageBatchRequestEntry{
MessageBody: message.Body,
Id: message.MessageId,
}
}
return result
}
func convertSuccessfulMessageToBatchRequestEntry(messages []*sqs.Message) []*sqs.DeleteMessageBatchRequestEntry {
result := make([]*sqs.DeleteMessageBatchRequestEntry, len(messages))
for i, message := range messages {
result[i] = &sqs.DeleteMessageBatchRequestEntry{
ReceiptHandle: message.ReceiptHandle,
Id: message.MessageId,
}
}
return result
}
func moveMessages(sourceQueueUrl string, destinationQueueUrl string, svc *sqs.SQS, numberOfMessages int) {
params := &sqs.ReceiveMessageInput{
QueueUrl: aws.String(sourceQueueUrl),
VisibilityTimeout: aws.Int64(2),
WaitTimeSeconds: aws.Int64(0),
MaxNumberOfMessages: aws.Int64(10),
}
log.Info(color.New(color.FgCyan).Sprintf("Starting to move messages..."))
fmt.Println()
term.HideCursor()
defer term.ShowCursor()
b := progress.NewInt(numberOfMessages)
b.Width = 40
b.StartDelimiter = color.New(color.FgCyan).Sprint("|")
b.EndDelimiter = color.New(color.FgCyan).Sprint("|")
b.Filled = color.New(color.FgCyan).Sprint("█")
b.Empty = color.New(color.FgCyan).Sprint("░")
b.Template(` {{.Bar}} {{.Text}}{{.Percent | printf "%3.0f"}}%`)
render := term.Renderer()
messagesProcessed := 0
for {
resp, err := svc.ReceiveMessage(params)
if len(resp.Messages) == 0 {
fmt.Println()
log.Info(color.New(color.FgCyan).Sprintf("Done. Moved %s messages", strconv.Itoa(numberOfMessages)))
return
}
if err != nil {
logAwsError("Failed to receive messages", err)
return
}
batch := &sqs.SendMessageBatchInput{
QueueUrl: aws.String(destinationQueueUrl),
Entries: convertToEntries(resp.Messages),
}
sendResp, err := svc.SendMessageBatch(batch)
if err != nil {
logAwsError("Failed to un-queue messages to the destination", err)
return
}
if len(sendResp.Failed) > 0 {
log.Error(color.New(color.FgRed).Sprintf("%s messages failed to enqueue, exiting", len(sendResp.Failed)))
return
}
if len(sendResp.Successful) == len(resp.Messages) {
deleteMessageBatch := &sqs.DeleteMessageBatchInput{
Entries: convertSuccessfulMessageToBatchRequestEntry(resp.Messages),
QueueUrl: aws.String(sourceQueueUrl),
}
deleteResp, err := svc.DeleteMessageBatch(deleteMessageBatch)
if err != nil {
logAwsError("Failed to delete messages from source queue", err)
return
}
if len(deleteResp.Failed) > 0 {
log.Error(color.New(color.FgRed).Sprintf("Error deleting messages, the following were not deleted\n %s", deleteResp.Failed))
return
}
messagesProcessed += len(resp.Messages)
}
// Increase the total if the approximation was under - avoids exception
if messagesProcessed > numberOfMessages {
b.Total = float64(messagesProcessed)
}
b.ValueInt(messagesProcessed)
render(b.String())
}
}