/
client.go
373 lines (302 loc) · 8.08 KB
/
client.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
package main
import (
"strings"
"os"
"io"
"errors"
"net/url"
"path/filepath"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/kms"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3/s3crypto"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/yookoala/realpath"
"fmt"
"strconv"
)
type S3Location struct {
Bucket string
Key string
}
var (
InvalidS3LocationError = errors.New("Invalid S3 Location")
InvalidS3FolderError = errors.New("S3 Key must point to an S3 folder")
FolderNotWritableError = errors.New("Folder is not writable")
NotExistError = errors.New("Folder does not exist")
workers int = 0
)
func init() {
val, ok := os.LookupEnv("NUM_WORKERS")
if ok {
parsedVal, err := strconv.Atoi(val)
if err == nil {
workers = parsedVal
}
}
if workers == 0 {
workers = 8
}
}
func NewS3Location(path string) (location *S3Location, err error) {
if !strings.Contains(path, "s3://") {
return nil, InvalidS3LocationError
}
u, err := url.Parse(path)
if err != nil {
return nil, err
}
location = &S3Location{
Bucket: u.Host,
Key: strings.Trim(u.Path, "/"),
}
return
}
type Client struct {
Session *session.Session
KmsId string
s3 *s3.S3
encryptionClient *s3crypto.EncryptionClient
decryptionClient *s3crypto.DecryptionClient
}
// Make load strategy configurable
func NewClient(sess *session.Session, kmsId string) (client *Client) {
client = &Client{
Session: sess,
KmsId: kmsId,
}
client.Init()
return
}
func (cli *Client) Init() {
handler := s3crypto.NewKMSKeyGenerator(kms.New(cli.Session), cli.KmsId)
crypto := s3crypto.AESGCMContentCipherBuilder(handler)
cli.s3 = s3.New(cli.Session)
cli.encryptionClient = s3crypto.NewEncryptionClient(cli.Session, crypto)
cli.decryptionClient = s3crypto.NewDecryptionClient(cli.Session)
}
func (cli *Client) UploadFile(source string, dest *S3Location) (error) {
file, openErr := os.Open(source)
if openErr != nil {
return openErr
}
defer file.Close()
input := &s3.PutObjectInput{
Body: aws.ReadSeekCloser(file),
Bucket: &dest.Bucket,
Key: &dest.Key,
ACL: aws.String("bucket-owner-full-control"),
ServerSideEncryption: aws.String("AES256"),
}
_, err2 := cli.encryptionClient.PutObject(input)
return err2
}
func (cli *Client) DownloadFile(source *S3Location, dest string) (error) {
// we want to support both encrypted and non-encrypted, so we call a HEAD to check
head, err := cli.s3.HeadObject(&s3.HeadObjectInput{
Bucket: &source.Bucket,
Key: &source.Key,
})
if err != nil {
return err
}
var output *s3.GetObjectOutput
input := &s3.GetObjectInput{
Bucket: &source.Bucket,
Key: &source.Key,
}
// from http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/package-summary.html
// key wrapping algorithm, x-amz-wrap-alg is always set to "kms" for CSE
if val, ok := head.Metadata["X-Amz-Wrap-Alg"]; ok && *val == "kms" {
output, err = cli.decryptionClient.GetObject(input)
} else {
output, err = cli.s3.GetObject(input)
}
if err != nil {
return err
}
dir := filepath.Dir(dest)
os.MkdirAll(dir, 0766)
file, openErr := os.Create(dest)
if openErr != nil {
return openErr
}
defer file.Close()
_, writeErr := io.Copy(file, output.Body)
return writeErr
}
func (cli *Client) DownloadFolder(source *S3Location, dest string) (error) {
// validate the destination
if ok, _ := IsDirWritable(dest); !ok {
return FolderNotWritableError
}
// validate the source
if err := cli.validateFolderKey(source); err != nil {
fmt.Printf("Unable to validate folder key\n")
return err
}
startIdx := len(source.Key)
p := NewWorkerPool(workers)
tf := func(item *S3Location) (func () error) {
return func() error {
destFile := strings.Trim(item.Key[startIdx:], "/")
fmt.Printf("Downloading %v ...\n", destFile)
return cli.DownloadFile(item, filepath.Join(dest, destFile))
}
}
errCh := cli.listObjects(source, p, tf)
finalErr := monitorPoolError(p, errCh)
if finalErr == io.EOF {
return nil
}
return finalErr
}
func (cli *Client) UploadFolder(source string, dest *S3Location) (error) {
realPath, err := realpath.Realpath(source)
if err != nil {
return err
}
stat, err := os.Stat(realPath)
if err != nil {
return err
}
if !stat.IsDir() {
return NotExistError
}
p := NewWorkerPool(workers)
errCh := make(chan error)
// task factory function
tf := func(key string) (func() error) {
return func() error {
sourceFile := filepath.Join(source, key)
destFile := &S3Location{dest.Bucket, fmt.Sprintf("%v/%v", dest.Key, key)}
fmt.Printf("Uploading %v\n", key)
return cli.UploadFile(sourceFile, destFile)
}
}
go func() {
startIdx := len(realPath)
upload := func(path string, f os.FileInfo, err error) error {
// if we have no error and this is a file, then we submit the task
if err == nil && !f.IsDir() {
key := path[startIdx+1:]
err = p.SubmitFunc(tf(key))
}
return err
}
err := filepath.Walk(realPath, upload)
if err == nil {
p.Stop() // stop the pool to drain all current task
errCh <- io.EOF
} else {
errCh <- err
}
}()
finalErr := monitorPoolError(p, errCh)
return finalErr
}
func (cli *Client) IsFile(loc *S3Location) (bool) {
svc := cli.s3
_, err := svc.HeadObject(&s3.HeadObjectInput{
Bucket: &loc.Bucket,
Key: &loc.Key,
})
return err == nil
}
// Validate S3 location for download. It will make sure that the location is not pointed
// to an S3 file
func (cli *Client) validateFolderKey(loc *S3Location) (error) {
svc := s3.New(cli.Session)
// just make sure this is not a file
if len(loc.Key) > 0 {
_, err := svc.GetObject(&s3.GetObjectInput{
Bucket: &loc.Bucket,
Key: &loc.Key,
})
if err != nil {
// it's okie that the key does not exist
if awsErr, ok := err.(awserr.Error); ok {
if awsErr.Code() != s3.ErrCodeNoSuchKey {
return err
}
} else {
return err
}
} else {
return InvalidS3FolderError
}
}
return nil
}
// List object from an S3Location and yielding the result
func (cli *Client) listObjects(location *S3Location, p *WorkerPool,
tf func(*S3Location) (func() error)) (errCh chan error) {
errCh = make(chan error)
svc := s3.New(cli.Session)
go func() {
var marker string
for {
output, err := svc.ListObjects(&s3.ListObjectsInput{
Bucket: &location.Bucket,
Prefix: &location.Key,
Marker: &marker,
})
if err == nil {
for _, object := range output.Contents {
// skip directory and instruction file
if !strings.HasSuffix(*object.Key, "/") &&
!strings.HasSuffix(*object.Key, s3crypto.DefaultInstructionKeySuffix) {
err = p.SubmitFunc(tf(&S3Location{
Bucket: location.Bucket,
Key: *object.Key,
}))
if err != nil {
break
}
}
marker = *object.Key
}
// continue if there is no error
if err == nil {
if *output.IsTruncated {
// if NextMarker is available, then use it
if output.NextMarker != nil {
marker = *output.NextMarker
}
} else {
err = io.EOF
}
}
}
if err != nil {
p.Stop()
errCh <- err
break
}
}
}()
return
}
func monitorPoolError(p *WorkerPool, errCh chan error) error {
var finalErr error
for {
done := false
select {
case t := <- p.ResultCh:
if t.Err != nil {
fmt.Fprint(os.Stderr, fmt.Sprintf("%v\n", t.Err))
p.Stop()
}
case finalErr = <- errCh:
done = true
}
if done {
break
}
}
if finalErr == io.EOF {
return nil
}
return finalErr
}