-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinbound.go
More file actions
317 lines (279 loc) · 8.57 KB
/
Copy pathinbound.go
File metadata and controls
317 lines (279 loc) · 8.57 KB
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
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/url"
"time"
"os"
"path/filepath"
amqp "github.com/rabbitmq/amqp091-go"
log "github.com/sirupsen/logrus"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
// S3Event represents the structure of an S3 event notification
type S3Event struct {
EventName string `json:"EventName"`
Records []S3Record `json:"Records"`
}
type S3Record struct {
S3 S3Info `json:"s3"`
}
type S3Info struct {
Bucket BucketInfo `json:"bucket"`
Object ObjectInfo `json:"object"`
}
type BucketInfo struct {
Name string `json:"name"`
}
type ObjectInfo struct {
Key string `json:"key"`
Size float64 `json:"size"`
}
var connections []*amqp.Connection
// nolint:gocognit,funlen // This function handles the main AMQP processing logic
func inbound(in Inbound) {
inboundWithContext(context.Background(), in)
}
func inboundWithContext(ctx context.Context, in Inbound) {
lf := log.Fields{
"workflow": in.Name,
}
u, err := url.Parse(in.Source)
if err != nil {
log.WithFields(lf).Error("failed to parse AMQP connection string: ", err)
return
}
lf = log.Fields{
"workflow": in.Name,
"source": u.Redacted(),
"exchange": in.Exchange,
"queue": in.Queue,
}
log.WithFields(lf).Info("configuring AMQP client for '", in.Description, "'")
// Reconnection loop
for attempt := 0; ; attempt++ {
select {
case <-ctx.Done():
log.WithFields(lf).Info("inbound cancelled")
return
default:
}
amqpConfig := amqp.Config{
Properties: amqp.NewConnectionProperties(),
}
amqpConfig.Properties.SetClientConnectionName("bucketsyncd")
conn, err := amqp.DialConfig(in.Source, amqpConfig)
if err != nil {
// Exponential backoff capped at 5 minutes, avoiding int→uint overflow
backoffSeconds := 1
for i := 0; i < attempt && backoffSeconds < 300; i++ {
backoffSeconds *= 2
}
if backoffSeconds > 300 {
backoffSeconds = 300
}
log.WithFields(lf).WithFields(log.Fields{
"attempt": attempt + 1,
"backoff": backoffSeconds,
"error": err,
}).Error("failed to connect to AMQP service, retrying")
time.Sleep(time.Duration(backoffSeconds) * time.Second)
continue
}
log.WithFields(lf).Info("successfully connected to AMQP service")
connections = append(connections, conn)
// Reset attempt counter on successful connection
attempt = 0
// Channel for connection close notifications
connCloseChan := make(chan *amqp.Error)
conn.NotifyClose(connCloseChan)
// Bind to message queue
channel, err := conn.Channel()
if err != nil {
log.WithFields(lf).Error("failed to declare AMQP channel: ", err)
if closeErr := conn.Close(); closeErr != nil {
log.WithFields(lf).Error("failed to close connection: ", closeErr)
}
continue
}
err = channel.QueueBind(
in.Queue,
in.Exchange,
in.Exchange,
false,
nil,
)
if err != nil {
log.WithFields(lf).Error("failed to bind to AMQP queue: ", err)
if closeErr := conn.Close(); closeErr != nil {
log.WithFields(lf).Error("failed to close connection: ", closeErr)
}
continue
}
log.WithFields(lf).Debug("queue bound to exchange")
// Consume messages
deliveries, err := channel.Consume(
in.Queue,
"bucketsyncd",
false,
false,
false,
false,
nil,
)
if err != nil {
log.WithFields(lf).Error("failed to consume messages from AMQP queue: ", err)
if closeErr := conn.Close(); closeErr != nil {
log.WithFields(lf).Error("failed to close connection: ", closeErr)
}
continue
}
log.WithFields(lf).Info("AMQP consumer started, processing messages")
// Message processing loop — use a label so inner breaks reach the reconnection loop
messageLoop:
for {
select {
case d, ok := <-deliveries:
if !ok {
log.WithFields(lf).Warn("deliveries channel closed")
if conn != nil && !conn.IsClosed() {
if closeErr := conn.Close(); closeErr != nil {
log.WithFields(lf).Error("failed to close connection: ", closeErr)
}
}
log.WithFields(lf).Info("reconnecting to AMQP service in 5 seconds")
time.Sleep(5 * time.Second)
break messageLoop
}
// Parse JSON payload
var s3Event S3Event
if err := json.Unmarshal(d.Body, &s3Event); err != nil {
log.WithFields(lf).Error("failed to parse JSON payload: ", err)
if nackErr := d.Nack(false, true); nackErr != nil { // Requeue for retry
log.WithFields(lf).Error("failed to nack message: ", nackErr)
}
continue
}
// Process each record in the event
for _, record := range s3Event.Records {
key, err := url.QueryUnescape(record.S3.Object.Key)
if err != nil {
log.WithFields(lf).Errorf("invalid URL-encoded key: %s", record.S3.Object.Key)
if nackErr := d.Nack(false, false); nackErr != nil { // Don't requeue invalid messages
log.WithFields(lf).Error("failed to nack message: ", nackErr)
}
continue
}
log.WithFields(lf).WithFields(log.Fields{
"bucket": record.S3.Bucket.Name,
"key": key,
"size": record.S3.Object.Size,
}).Debugf("event '%s' received", s3Event.EventName)
if err := downloadRecord(ctx, lf, record.S3.Bucket.Name, key, in); err != nil {
log.WithFields(lf).Error("failed to process record: ", err)
if nackErr := d.Nack(false, true); nackErr != nil {
log.WithFields(lf).Error("failed to nack message: ", nackErr)
}
continue
}
// Acknowledge queued message after successful processing
if err := d.Ack(false); err != nil {
log.WithFields(lf).Error("failed to acknowledge AMQP message: ", err)
}
}
case connErr, ok := <-connCloseChan:
if !ok {
log.WithFields(lf).Warn("connection close channel closed")
} else {
log.WithFields(lf).WithFields(log.Fields{
"error": connErr,
}).Warn("AMQP connection closed, attempting reconnection")
}
if conn != nil && !conn.IsClosed() {
if closeErr := conn.Close(); closeErr != nil {
log.WithFields(lf).Error("failed to close connection: ", closeErr)
}
}
log.WithFields(lf).Info("reconnecting to AMQP service in 5 seconds")
time.Sleep(5 * time.Second)
break messageLoop
}
}
}
}
// downloadRecord fetches a single S3 object and writes it to the configured destination.
// Extracted from the message-processing loop so defers are scoped to the function call.
func downloadRecord(ctx context.Context, lf log.Fields, bucketName, key string, in Inbound) error {
// Determine remote credentials
creds := credentials.Credentials{}
credsFound := false
var remote Remote
configMutex.RLock()
for _, r := range config.Remotes {
if r.Name == in.Remote {
remote = r
creds = *credentials.NewStaticV4(r.AccessKey, r.SecretKey, "")
credsFound = true
break
}
}
configMutex.RUnlock()
if !credsFound {
return fmt.Errorf("no credentials found for remote %q", in.Remote)
}
log.WithFields(lf).Debugf("connecting to endpoint '%s'", remote.Endpoint)
mc, err := minio.New(remote.Endpoint, &minio.Options{
Creds: &creds,
Secure: true,
})
if err != nil {
return fmt.Errorf("failed to create MinIO client: %w", err)
}
fetchCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
minioObj, err := mc.GetObject(fetchCtx, bucketName, key, minio.GetObjectOptions{})
if err != nil {
return fmt.Errorf("failed to fetch object from MinIO: %w", err)
}
defer func() {
if err := minioObj.Close(); err != nil {
log.WithFields(lf).Error("failed to close object: ", err)
}
}()
stat, err := minioObj.Stat()
if err != nil {
return fmt.Errorf("failed to get object stat: %w", err)
}
localFilename := fmt.Sprintf("%s/%s", in.Destination, filepath.Base(key))
const filePerms = 0600
// #nosec G304 - This is intentional file creation in configured destination
localFile, err := os.OpenFile(localFilename, os.O_RDWR|os.O_CREATE, filePerms)
if err != nil {
return fmt.Errorf("failed to create local file: %w", err)
}
defer func() {
if err := localFile.Close(); err != nil {
log.WithFields(lf).Error("failed to close local file: ", err)
}
}()
if _, err := io.CopyN(localFile, minioObj, stat.Size); err != nil {
return fmt.Errorf("failed to copy file from reader: %w", err)
}
log.WithFields(lf).WithFields(log.Fields{
"filename": localFilename,
"size": stat.Size,
}).Info("retrieved remote object to local file")
message := fmt.Sprintf("Downloaded %s", filepath.Base(key))
SendNotification("bucketsyncd", message)
return nil
}
func inboundClose() {
for _, c := range connections {
if err := c.Close(); err != nil {
log.Errorf("unable to close AMQP connection: %s", err)
}
}
}