forked from drone-plugins/drone-s3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.go
320 lines (268 loc) · 7.25 KB
/
plugin.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
package main
import (
"mime"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/mattn/go-zglob"
log "github.com/sirupsen/logrus"
)
// Plugin defines the S3 plugin parameters.
type Plugin struct {
Endpoint string
Key string
Secret string
AssumeRole string
AssumeRoleSessionName string
Bucket string
UserRoleArn string
// if not "", enable server-side encryption
// valid values are:
// AES256
// aws:kms
Encryption string
// us-east-1
// us-west-1
// us-west-2
// eu-west-1
// ap-southeast-1
// ap-southeast-2
// ap-northeast-1
// sa-east-1
Region string
// Indicates the files ACL, which should be one
// of the following:
// private
// public-read
// public-read-write
// authenticated-read
// bucket-owner-read
// bucket-owner-full-control
Access string
// Sets the content type on each uploaded object based on a extension map
ContentType map[string]string
// Sets the content encoding on each uploaded object based on a extension map
ContentEncoding map[string]string
// Sets the Cache-Control header on each uploaded object based on a extension map
CacheControl map[string]string
// Sets the storage class, affects the storage backend costs
StorageClass string
// Copies the files from the specified directory.
// Regexp matching will apply to match multiple
// files
//
// Examples:
// /path/to/file
// /path/to/*.txt
// /path/to/*/*.txt
// /path/to/**
Source string
Target string
// Strip the prefix from the target path
StripPrefix string
// Exclude files matching this pattern.
Exclude []string
// Use path style instead of domain style.
//
// Should be true for minio and false for AWS.
PathStyle bool
// Dry run without uploading/
DryRun bool
}
// Exec runs the plugin
func (p *Plugin) Exec() error {
// normalize the target URL
if strings.HasPrefix(p.Target, "/") {
p.Target = p.Target[1:]
}
// create the client
conf := &aws.Config{
Region: aws.String(p.Region),
Endpoint: &p.Endpoint,
DisableSSL: aws.Bool(strings.HasPrefix(p.Endpoint, "http://")),
S3ForcePathStyle: aws.Bool(p.PathStyle),
}
if p.Key != "" && p.Secret != "" {
conf.Credentials = credentials.NewStaticCredentials(p.Key, p.Secret, "")
} else if p.AssumeRole != "" {
conf.Credentials = assumeRole(p.AssumeRole, p.AssumeRoleSessionName)
} else {
log.Warn("AWS Key and/or Secret not provided (falling back to ec2 instance profile)")
}
var client *s3.S3
sess, err := session.NewSession(conf)
if err != nil {
log.WithError(err).Errorln("could not instantiate session")
return err
}
// If user role ARN is set then assume role here
if len(p.UserRoleArn) > 0 {
confRoleArn := aws.Config{
Region: aws.String(p.Region),
Credentials: stscreds.NewCredentials(sess, p.UserRoleArn),
}
client = s3.New(sess, &confRoleArn)
} else {
client = s3.New(sess)
}
// find the bucket
log.WithFields(log.Fields{
"region": p.Region,
"endpoint": p.Endpoint,
"bucket": p.Bucket,
}).Info("Attempting to upload")
matches, err := matches(p.Source, p.Exclude)
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Error("Could not match files")
return err
}
for _, match := range matches {
stat, err := os.Stat(match)
if err != nil {
continue // should never happen
}
// skip directories
if stat.IsDir() {
continue
}
target := resolveKey(p.Target, match, p.StripPrefix)
contentType := matchExtension(match, p.ContentType)
contentEncoding := matchExtension(match, p.ContentEncoding)
cacheControl := matchExtension(match, p.CacheControl)
if contentType == "" {
contentType = mime.TypeByExtension(filepath.Ext(match))
if contentType == "" {
contentType = "application/octet-stream"
}
}
// log file for debug purposes.
log.WithFields(log.Fields{
"name": match,
"bucket": p.Bucket,
"target": target,
}).Info("Uploading file")
// when executing a dry-run we exit because we don't actually want to
// upload the file to S3.
if p.DryRun {
continue
}
f, err := os.Open(match)
if err != nil {
log.WithFields(log.Fields{
"error": err,
"file": match,
}).Error("Problem opening file")
return err
}
defer f.Close()
putObjectInput := &s3.PutObjectInput{
Body: f,
Bucket: &(p.Bucket),
Key: &target,
ACL: &(p.Access),
}
if contentType != "" {
putObjectInput.ContentType = aws.String(contentType)
}
if contentEncoding != "" {
putObjectInput.ContentEncoding = aws.String(contentEncoding)
}
if cacheControl != "" {
putObjectInput.CacheControl = aws.String(cacheControl)
}
if p.Encryption != "" {
putObjectInput.ServerSideEncryption = aws.String(p.Encryption)
}
if p.StorageClass != "" {
putObjectInput.StorageClass = &(p.StorageClass)
}
_, err = client.PutObject(putObjectInput)
if err != nil {
log.WithFields(log.Fields{
"name": match,
"bucket": p.Bucket,
"target": target,
"error": err,
}).Error("Could not upload file")
return err
}
f.Close()
}
return nil
}
// matches is a helper function that returns a list of all files matching the
// included Glob pattern, while excluding all files that matche the exclusion
// Glob pattners.
func matches(include string, exclude []string) ([]string, error) {
matches, err := zglob.Glob(include)
if err != nil {
return nil, err
}
if len(exclude) == 0 {
return matches, nil
}
// find all files that are excluded and load into a map. we can verify
// each file in the list is not a member of the exclusion list.
excludem := map[string]bool{}
for _, pattern := range exclude {
excludes, err := zglob.Glob(pattern)
if err != nil {
return nil, err
}
for _, match := range excludes {
excludem[match] = true
}
}
var included []string
for _, include := range matches {
_, ok := excludem[include]
if ok {
continue
}
included = append(included, include)
}
return included, nil
}
func matchExtension(match string, stringMap map[string]string) string {
for pattern := range stringMap {
matched, err := regexp.MatchString(pattern, match)
if err != nil {
panic(err)
}
if matched {
return stringMap[pattern]
}
}
return ""
}
func assumeRole(roleArn, roleSessionName string) *credentials.Credentials {
client := sts.New(session.New())
duration := time.Hour * 1
stsProvider := &stscreds.AssumeRoleProvider{
Client: client,
Duration: duration,
RoleARN: roleArn,
RoleSessionName: roleSessionName,
}
return credentials.NewCredentials(stsProvider)
}
// resolveKey is a helper function that returns s3 object key where file present at srcPath is uploaded to.
// srcPath is assumed to be in forward slash format
func resolveKey(target, srcPath, stripPrefix string) string {
key := filepath.Join(target, strings.TrimPrefix(srcPath, filepath.ToSlash(stripPrefix)))
key = filepath.ToSlash(key)
if !strings.HasPrefix(key, "/") {
key = "/" + key
}
return key
}