-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathsqs.go
225 lines (193 loc) · 5.36 KB
/
sqs.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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"strings"
"time"
"github.com/TylerBrock/colorjson"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/sqs"
"github.com/aws/aws-sdk-go-v2/service/sqs/types"
)
type sqsClient struct {
client sqsClientAPI
arn string
queueName string
queueURL string
}
type sqsClientAPI interface {
CreateQueue(ctx context.Context, params *sqs.CreateQueueInput, optFns ...func(*sqs.Options)) (*sqs.CreateQueueOutput, error)
DeleteQueue(ctx context.Context, params *sqs.DeleteQueueInput, optFns ...func(*sqs.Options)) (*sqs.DeleteQueueOutput, error)
ReceiveMessage(ctx context.Context, params *sqs.ReceiveMessageInput, optFns ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error)
DeleteMessageBatch(ctx context.Context, params *sqs.DeleteMessageBatchInput, optFns ...func(*sqs.Options)) (*sqs.DeleteMessageBatchOutput, error)
}
func newSQSClient(cfg aws.Config, accountID, queueName string) *sqsClient {
return &sqsClient{
client: sqs.NewFromConfig(cfg),
arn: fmt.Sprintf("arn:aws:sqs:%s:%s:%s", cfg.Region, accountID, queueName),
queueName: queueName,
}
}
func (s *sqsClient) createQueue(ctx context.Context, ruleArn string) error {
resp, err := s.client.CreateQueue(ctx, &sqs.CreateQueueInput{
QueueName: aws.String(s.queueName),
Attributes: map[string]string{
"Policy": fmt.Sprintf(`{
"Version": "2012-10-17",
"Id": "%s",
"Statement": [{
"Sid": "Sid1579089564623",
"Effect": "Allow",
"Principal": {
"Service": "events.amazonaws.com"
},
"Action": "SQS:SendMessage",
"Resource": "%s",
"Condition": {
"ArnEquals": {
"aws:SourceArn": "%s"
}
}
}]
}`, runID, s.arn, ruleArn),
"SqsManagedSseEnabled": "true",
},
})
if err != nil {
log.Printf("sqs.CreateQueue error: %s", err)
return err
}
s.queueURL = *resp.QueueUrl
return err
}
func (s *sqsClient) deleteQueue(ctx context.Context) error {
_, err := s.client.DeleteQueue(ctx, &sqs.DeleteQueueInput{
QueueUrl: aws.String(s.queueURL),
})
if err != nil {
log.Printf("sqs.DeleteQueue error: %s", err)
return err
}
return err
}
func (s *sqsClient) pollQueue(ctx context.Context, signalChan chan os.Signal, prettyJSON bool) {
log.Printf("polling queue %s ...", s.queueURL)
log.Printf("press ctr+c to stop")
defer close(signalChan)
for {
// goroutine
select {
case <-signalChan:
log.Printf("stopping poller...")
return
default:
resp, err := s.client.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{
QueueUrl: aws.String(s.queueURL),
MaxNumberOfMessages: 10,
WaitTimeSeconds: 5,
MessageAttributeNames: []string{"All"},
})
// handle recovery from 'dial tcp' errors
if err != nil && strings.Contains(err.Error(), "dial tcp") {
log.Printf("sqs.ReceiveMessage error: %s", err)
// backoff
time.Sleep(10 * time.Second)
continue
}
// handle all other errors
if err != nil {
log.Printf("sqs.ReceiveMessage error: %s", err)
return
}
if len(resp.Messages) == 0 {
continue
}
entries := []types.DeleteMessageBatchRequestEntry{}
for _, m := range resp.Messages {
entries = append(entries, types.DeleteMessageBatchRequestEntry{
Id: m.MessageId,
ReceiptHandle: m.ReceiptHandle,
})
if prettyJSON {
var j map[string]interface{}
err := json.Unmarshal([]byte(*m.Body), &j)
if err != nil {
return
}
f := colorjson.NewFormatter()
f.Indent = 2
pj, _ := f.Marshal(j)
log.Println(string(pj))
continue
}
log.Printf("%s", *m.Body)
}
// cleanup messages
_, err = s.client.DeleteMessageBatch(ctx, &sqs.DeleteMessageBatchInput{
QueueUrl: aws.String(s.queueURL),
Entries: entries,
})
if err != nil {
log.Printf("sqs.DeleteMessageBatch error: %s", err)
}
}
}
}
func (s *sqsClient) pollQueueCI(ctx context.Context, signalChan chan os.Signal, prettyJSON bool, timeout int64) {
log.Printf("polling queue %s ...", s.queueURL)
defer close(signalChan)
for {
// goroutine
select {
case <-signalChan:
log.Printf("stopping poller...")
return
default:
resp, err := s.client.ReceiveMessage(ctx, &sqs.ReceiveMessageInput{
QueueUrl: aws.String(s.queueURL),
MaxNumberOfMessages: 10,
WaitTimeSeconds: 5,
MessageAttributeNames: []string{"All"},
})
if err != nil {
log.Printf("sqs.ReceiveMessage error: %s", err)
return
}
if len(resp.Messages) == 0 {
continue
}
entries := []types.DeleteMessageBatchRequestEntry{}
for _, m := range resp.Messages {
entries = append(entries, types.DeleteMessageBatchRequestEntry{
Id: m.MessageId,
ReceiptHandle: m.ReceiptHandle,
})
if prettyJSON {
var j map[string]interface{}
err := json.Unmarshal([]byte(*m.Body), &j)
if err != nil {
return
}
f := colorjson.NewFormatter()
f.Indent = 2
pj, _ := f.Marshal(j)
log.Printf("received event: %s", string(pj))
continue
}
log.Printf("received event: %s", *m.Body)
}
// cleanup messages
_, err = s.client.DeleteMessageBatch(ctx, &sqs.DeleteMessageBatchInput{
QueueUrl: aws.String(s.queueURL),
Entries: entries,
})
if err != nil {
log.Printf("sqs.DeleteMessageBatch error: %s", err)
}
return
}
}
}