-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy paths3.go
338 lines (290 loc) · 7.12 KB
/
s3.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
package main
import (
"context"
"crypto/md5"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"mime"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/mattn/go-zglob"
"github.com/opencontainers/selinux/pkg/pwalkdir"
)
type S3Upload struct {
Config *Config
Conn *s3.S3
SourcePath string
expires *time.Time
prefixBytes int
}
// FileData contains data of file to be uploaded
type FileData struct {
origPath string
Path string `json:"path"`
FilePrefix string `json:"hash"`
UploadedTs int64 `json:"ts,omitempty"`
MD5Hash string `json:"-"`
}
func NewS3Upload(cfg *Config) (*S3Upload, error) {
var err error
s3c := &S3Upload{Config: cfg}
s3c.SourcePath, err = filepath.Abs(cfg.S3.Source)
if err != nil {
return nil, err
}
if cfg.S3.ExpiresAfterSeconds != 0 {
t := time.Now().UTC().Add(time.Second * time.Duration(cfg.S3.ExpiresAfterSeconds))
s3c.expires = &t
}
if hashPrefixBytesFlag != nil && prefixFlag != nil {
s3c.prefixBytes = int(*hashPrefixBytesFlag)
if s3c.prefixBytes > 16 {
s3c.prefixBytes = 16
}
}
return s3c, nil
}
// Connect opens connection to AWS and sets up session
func (s *S3Upload) Connect() error {
var err error
s.Conn, err = s.newSession()
if err != nil {
return err
}
return nil
}
func (s *S3Upload) newSession() (*s3.S3, error) {
cfg := s.Config
awsConfig := &aws.Config{}
sess, err := session.NewSession(awsConfig)
if err != nil {
return nil, err
}
sess.Config.WithCredentials(credentials.NewStaticCredentials(cfg.S3.AccessKey, cfg.S3.SecretKey, ""))
region := cfg.S3.Region
if region == "" {
region, err = s3manager.GetBucketRegion(context.Background(), sess, cfg.S3.Bucket, "us-west-2")
if err != nil {
return nil, err
}
}
if region == "" {
return nil, errors.New("unknown region")
}
sess.Config.WithRegion(region)
return s3.New(sess), nil
}
func (s *S3Upload) isUploadableFile(path string) (bool, error) {
for _, pat := range s.Config.S3.Ignore {
match, err := zglob.Match(pat, path)
if err != nil {
return false, err
}
if match {
return false, nil
}
}
return true, nil
}
func (s *S3Upload) sourceFiles() ([]*FileData, error) {
var files []*FileData
source := s.SourcePath
err := pwalkdir.Walk(source, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
// Skip ignored files
cpath := strings.TrimPrefix(path, s.SourcePath)
if cpath == "" {
return nil
}
cpath = cpath[1:]
ok, err := s.isUploadableFile(cpath)
if err != nil {
return err
}
if !ok {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
// Skip if path is directory
if d.IsDir() {
return nil
}
// calculate md5-hash of file
h := md5.New()
if _, err := io.Copy(h, file); err != nil {
return err
}
md5Hash := h.Sum(nil)
// add md5 hash as prefix if required
hashPrefix := ""
if *hashPrefixFlag {
hashPrefix = Base64UrlEncode(md5Hash[:s.prefixBytes])
}
destPath := filepath.Join("/", hashPrefix, s.Config.S3.Prefix, cpath)
// Normalize path separators on the S3 side to a forward slash, for OSes like Windows
if os.PathSeparator != '/' {
destPath = strings.Replace(destPath, string(os.PathSeparator), "/", -1)
}
// Add to the list of files to upload
files = append(
files,
&FileData{
origPath: path,
Path: destPath,
MD5Hash: fmt.Sprintf("%x", md5Hash),
FilePrefix: hashPrefix,
},
)
return nil
})
if err != nil {
return nil, err
}
return files, nil
}
func (s *S3Upload) uploadFile(fileData *FileData, dryrun bool) (int, error) {
s3c := s.Conn
file, err := os.Open(fileData.origPath)
if err != nil {
return 0, err
}
defer file.Close()
// check if object exists if specified in flags
if *syncFlag {
headOutput, err := s3c.HeadObject(&s3.HeadObjectInput{
Bucket: aws.String(s.Config.S3.Bucket),
Key: aws.String(fileData.Path),
})
if err == nil {
// file exists on S3, check if we need to proceed with upload
fileData.UploadedTs = headOutput.LastModified.Unix()
if headOutput.ETag != nil && strings.Trim(*headOutput.ETag, "\"") == fileData.MD5Hash {
fmt.Printf("File %s hasn't been changed (copy on S3 has the same md5-hash in ETag)\n",
fileData.Path)
return 0, nil
}
} else {
// check error, return if it is not 404
if reqErr, ok := err.(awserr.RequestFailure); !ok {
return 0, err
} else if reqErr.StatusCode() != http.StatusNotFound {
return 0, err
}
}
}
if dryrun {
fmt.Printf("[DRYRUN] uploading %s ...\n", fileData.Path)
return 0, nil
}
fmt.Printf("uploading %s ...\n", fileData.Path)
mimeType := mime.TypeByExtension(filepath.Ext(fileData.origPath))
if mimeType == "" {
mimeType = "application/octet-stream"
}
acl := s.Config.S3.ACL
if acl == "" {
acl = "private"
}
obj := &s3.PutObjectInput{
Bucket: aws.String(s.Config.S3.Bucket),
Key: aws.String(fileData.Path),
ACL: aws.String(acl),
ContentType: aws.String(mimeType),
Body: file,
Expires: s.expires,
}
if s.Config.S3.CacheControl != "" {
obj.CacheControl = aws.String(s.Config.S3.CacheControl)
}
req, _ := s3c.PutObjectRequest(obj)
if err := req.Send(); err != nil {
return 0, err
}
// request new object to get actual update timestamp
if headOutput, err := s3c.HeadObject(&s3.HeadObjectInput{
Bucket: aws.String(s.Config.S3.Bucket),
Key: aws.String(fileData.Path),
}); err != nil {
return 0, err
} else {
fileData.UploadedTs = headOutput.LastModified.Unix()
}
return 1, nil
}
func (s *S3Upload) Upload(parallel int, dryrun bool) (uint64, error) {
// get list of files with data
files, err := s.sourceFiles()
if err != nil {
return 0, err
}
fch := make(chan *FileData, len(files))
for _, fileData := range files {
fch <- fileData
}
close(fch)
var num uint64
var wg sync.WaitGroup
for i := 0; i < parallel; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
for fileData := range fch {
numRetries := 30
RETRY:
n, err := s.uploadFile(fileData, dryrun)
if err != nil {
_, ok := err.(awserr.Error)
if ok {
numRetries -= 1
if numRetries > 0 {
// retry in 1 second
fmt.Printf("failed to upload %s (error:%v), retrying in 1 second ...\n", fileData.origPath, err)
time.Sleep(1 * time.Second)
goto RETRY
} else {
panic(err)
}
} else {
panic(fmt.Sprintf("unknown error! %v", err))
}
}
atomic.AddUint64(&num, uint64(n))
}
}(i)
}
wg.Wait()
if *manifestFlag != "" {
fmt.Printf("Writing manifest file to: %s\n", *manifestFlag)
manifestFile, err := os.Create(*manifestFlag)
if err != nil {
return 0, err
}
defer manifestFile.Close()
enc := json.NewEncoder(manifestFile)
enc.SetIndent("", " ")
if err := enc.Encode(files); err != nil {
return 0, err
}
}
return num, nil
}