forked from goAWS/cloudformationresources
-
Notifications
You must be signed in to change notification settings - Fork 1
/
zipToS3BucketResource.go
193 lines (180 loc) · 5.28 KB
/
zipToS3BucketResource.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
package cloudformationresources
import (
"archive/zip"
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime"
"os"
"path"
"strings"
"github.com/Sirupsen/logrus"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
gocf "github.com/mweagle/go-cloudformation"
)
// DefaultManifestName is the name of the file that will be created
// at the root of the S3 bucket with user-supplied metadata
const DefaultManifestName = "MANIFEST.json"
// ZipToS3BucketResource manages populating an S3 bucket with the contents
// of a ZIP file...
type ZipToS3BucketResource struct {
GoAWSCustomResource
SrcBucket *gocf.StringExpr
SrcKeyName *gocf.StringExpr
DestBucket *gocf.StringExpr
ManifestName string
Manifest map[string]interface{}
}
func (command ZipToS3BucketResource) unzip(session *session.Session,
logger *logrus.Logger) (map[string]interface{}, error) {
// Fetch the ZIP contents and unpack them to the S3 bucket
svc := s3.New(session)
s3Object, s3ObjectErr := svc.GetObject(&s3.GetObjectInput{
Bucket: aws.String(command.SrcBucket.Literal),
Key: aws.String(command.SrcKeyName.Literal),
})
if nil != s3ObjectErr {
return nil, s3ObjectErr
}
// Put all the ZIP contents to the bucket
defer s3Object.Body.Close()
destFile, destFileErr := ioutil.TempFile("", "s3")
if nil != destFileErr {
return nil, destFileErr
}
defer os.Remove(destFile.Name())
_, copyErr := io.Copy(destFile, s3Object.Body)
if nil != copyErr {
return nil, copyErr
}
zipReader, zipErr := zip.OpenReader(destFile.Name())
if nil != zipErr {
return nil, zipErr
}
// Iterate through the files in the archive,
// printing some of their contents.
// TODO - refactor to a worker pool
totalFiles := 0
for _, eachFile := range zipReader.File {
totalFiles++
stream, streamErr := eachFile.Open()
if nil != streamErr {
return nil, streamErr
}
bodySource, bodySourceErr := ioutil.ReadAll(stream)
if nil != bodySourceErr {
return nil, bodySourceErr
}
normalizedName := strings.TrimLeft(eachFile.Name, "/")
// Mime type?
fileExtension := path.Ext(eachFile.Name)
mimeType := mime.TypeByExtension(fileExtension)
if "" == mimeType {
mimeType = "application/octet-stream"
}
if len(normalizedName) > 0 {
s3PutObject := &s3.PutObjectInput{
Body: bytes.NewReader(bodySource),
Bucket: aws.String(command.DestBucket.Literal),
Key: aws.String(fmt.Sprintf("/%s", eachFile.Name)),
ContentType: aws.String(mimeType),
}
_, err := svc.PutObject(s3PutObject)
if err != nil {
return nil, err
}
}
stream.Close()
}
// Need to add the manifest data iff defined
if nil != command.Manifest {
manifestBytes, manifestErr := json.Marshal(command.Manifest)
if nil != manifestErr {
return nil, manifestErr
}
name := command.ManifestName
if "" == name {
name = DefaultManifestName
}
s3PutObject := &s3.PutObjectInput{
Body: bytes.NewReader(manifestBytes),
Bucket: aws.String(command.DestBucket.Literal),
Key: aws.String(name),
ContentType: aws.String("application/json"),
}
_, err := svc.PutObject(s3PutObject)
if err != nil {
return nil, err
}
}
// Log some information
logger.WithFields(logrus.Fields{
"TotalFileCount": totalFiles,
"ArchiveSize": *s3Object.ContentLength,
"S3Bucket": command.DestBucket,
}).Info("Expanded ZIP archive")
// All good
return nil, nil
}
func (command ZipToS3BucketResource) create(session *session.Session,
logger *logrus.Logger) (map[string]interface{}, error) {
return command.unzip(session, logger)
}
func (command ZipToS3BucketResource) update(session *session.Session,
logger *logrus.Logger) (map[string]interface{}, error) {
return command.unzip(session, logger)
}
func (command ZipToS3BucketResource) delete(session *session.Session,
logger *logrus.Logger) (map[string]interface{}, error) {
// Remove all objects from the bucket
totalItemsDeleted := 0
svc := s3.New(session)
deleteItemsHandler := func(objectOutputs *s3.ListObjectsOutput, lastPage bool) bool {
params := &s3.DeleteObjectsInput{
Bucket: aws.String(command.DestBucket.Literal),
Delete: &s3.Delete{ // Required
Objects: []*s3.ObjectIdentifier{},
Quiet: aws.Bool(true),
},
}
for _, eachObject := range objectOutputs.Contents {
totalItemsDeleted++
params.Delete.Objects = append(params.Delete.Objects, &s3.ObjectIdentifier{
Key: eachObject.Key,
})
}
_, deleteResultErr := svc.DeleteObjects(params)
return nil == deleteResultErr
}
// Walk the bucket and cleanup...
params := &s3.ListObjectsInput{
Bucket: aws.String(command.DestBucket.Literal),
MaxKeys: aws.Int64(1000),
}
err := svc.ListObjectsPages(params, deleteItemsHandler)
if nil != err {
return nil, err
}
// Cleanup the Manifest iff defined
var deleteErr error
if nil != command.Manifest {
name := command.ManifestName
if "" == name {
name = DefaultManifestName
}
manifestDeleteParams := &s3.DeleteObjectInput{
Bucket: aws.String(command.DestBucket.Literal),
Key: aws.String(name),
}
_, deleteErr = svc.DeleteObject(manifestDeleteParams)
logger.WithFields(logrus.Fields{
"TotalDeletedCount": totalItemsDeleted,
"S3Bucket": command.DestBucket,
}).Info("Purged S3 Bucket")
}
return nil, deleteErr
}