/
zipToS3BucketResource.go
254 lines (231 loc) · 7.23 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
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
package resources
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"io"
"io/ioutil"
"mime"
"os"
"path"
"strings"
awsv2 "github.com/aws/aws-sdk-go-v2/aws"
awsv2S3 "github.com/aws/aws-sdk-go-v2/service/s3"
awsv2S3Types "github.com/aws/aws-sdk-go-v2/service/s3/types"
gof "github.com/awslabs/goformation/v5/cloudformation"
"github.com/pkg/errors"
"github.com/rs/zerolog"
)
// 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"
// ZipToS3BucketResourceRequest is the data request made to a ZipToS3BucketResource
// lambda handler
type ZipToS3BucketResourceRequest struct {
CustomResourceRequest
SrcBucket string
SrcKeyName string
DestBucket string
ManifestName string
Manifest map[string]interface{}
}
// ZipToS3BucketResource manages populating an S3 bucket with the contents
// of a ZIP file...
type ZipToS3BucketResource struct {
gof.CustomResource
}
func (command ZipToS3BucketResource) unzip(ctx context.Context,
awsConfig awsv2.Config,
event *CloudFormationLambdaEvent,
logger *zerolog.Logger) (map[string]interface{}, error) {
request := ZipToS3BucketResourceRequest{}
unmarshalErr := json.Unmarshal(event.ResourceProperties, &request)
if unmarshalErr != nil {
return nil, unmarshalErr
}
logger.Info().
Interface("CloudFormationEvent", *event).
Msg("Incoming unzip event")
// Fetch the ZIP contents and unpack them to the S3 bucket
svc := awsv2S3.NewFromConfig(awsConfig)
s3Object, s3ObjectErr := svc.GetObject(ctx, &awsv2S3.GetObjectInput{
Bucket: awsv2.String(request.SrcBucket),
Key: awsv2.String(request.SrcKeyName),
})
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.TrimPrefix(eachFile.Name, "/")
logger.Info().
Str("Name", eachFile.Name).
Int64("CompressedSize", int64(eachFile.CompressedSize64)).
Int64("UncompressedSize", int64(eachFile.UncompressedSize64)).
Msg("ZipEntry")
// Mime type?
fileExtension := path.Ext(eachFile.Name)
mimeType := mime.TypeByExtension(fileExtension)
if mimeType == "" {
mimeType = "application/octet-stream"
}
if len(normalizedName) > 0 {
s3PutObject := &awsv2S3.PutObjectInput{
Body: bytes.NewReader(bodySource),
Bucket: awsv2.String(request.DestBucket),
Key: awsv2.String(normalizedName),
ContentType: awsv2.String(mimeType),
}
_, err := svc.PutObject(ctx, s3PutObject)
if err != nil {
return nil, err
}
logger.Info().
Str("Bucket", request.DestBucket).
Str("Key", *s3PutObject.Key).
Msg("Unzipping object")
}
errClose := stream.Close()
if errClose != nil {
return nil, errors.Wrapf(errClose, "Failed to close S3 PutObject stream")
}
}
// Need to add the manifest data iff defined
if nil != request.Manifest {
manifestBytes, manifestErr := json.Marshal(request.Manifest)
if nil != manifestErr {
return nil, manifestErr
}
name := request.ManifestName
if name == "" {
name = DefaultManifestName
}
s3PutObject := &awsv2S3.PutObjectInput{
Body: bytes.NewReader(manifestBytes),
Bucket: awsv2.String(request.DestBucket),
Key: awsv2.String(name),
ContentType: awsv2.String("application/json"),
}
_, err := svc.PutObject(context.Background(), s3PutObject)
if err != nil {
return nil, err
}
}
// Log some information
logger.Info().
Int("TotalFileCount", totalFiles).
Int64("ArchiveSize", s3Object.ContentLength).
Interface("S3Bucket", request.DestBucket).
Msg("Expanded ZIP archive")
// All good
return nil, nil
}
// IAMPrivileges returns the IAM privs for this custom action
func (command *ZipToS3BucketResource) IAMPrivileges() []string {
// Empty implementation - s3Site.go handles setting up the IAM privs for this.
return []string{}
}
// Create implements the custom resource create operation
func (command ZipToS3BucketResource) Create(ctx context.Context, awsConfig awsv2.Config,
event *CloudFormationLambdaEvent,
logger *zerolog.Logger) (map[string]interface{}, error) {
return command.unzip(ctx, awsConfig, event, logger)
}
// Update implements the custom resource update operation
func (command ZipToS3BucketResource) Update(ctx context.Context, awsConfig awsv2.Config,
event *CloudFormationLambdaEvent,
logger *zerolog.Logger) (map[string]interface{}, error) {
return command.unzip(ctx, awsConfig, event, logger)
}
// Delete implements the custom resource delete operation
func (command ZipToS3BucketResource) Delete(ctx context.Context, awsConfig awsv2.Config,
event *CloudFormationLambdaEvent,
logger *zerolog.Logger) (map[string]interface{}, error) {
request := ZipToS3BucketResourceRequest{}
unmarshalErr := json.Unmarshal(event.ResourceProperties, &request)
if unmarshalErr != nil {
return nil, unmarshalErr
}
// Remove all objects from the bucket
totalItemsDeleted := 0
svc := awsv2S3.NewFromConfig(awsConfig)
deleteItemsHandler := func(objectOutputs *awsv2S3.ListObjectsOutput) {
params := &awsv2S3.DeleteObjectsInput{
Bucket: awsv2.String(request.DestBucket),
Delete: &awsv2S3Types.Delete{ // Required
Objects: []awsv2S3Types.ObjectIdentifier{},
Quiet: true,
},
}
for _, eachObject := range objectOutputs.Contents {
totalItemsDeleted++
params.Delete.Objects = append(params.Delete.Objects,
awsv2S3Types.ObjectIdentifier{
Key: eachObject.Key,
})
}
_, deleteResultErr := svc.DeleteObjects(ctx, params)
if deleteResultErr != nil {
logger.Warn().
Interface("DeleteObjectsErr", deleteResultErr).
Msg("Failed to delete object")
}
}
// Walk the bucket and cleanup...
params := &awsv2S3.ListObjectsInput{
Bucket: awsv2.String(request.DestBucket),
MaxKeys: 1000,
}
listObjResponse, listObjectResponsErr := svc.ListObjects(context.Background(), params)
if nil != listObjectResponsErr {
return nil, listObjectResponsErr
}
// Delete all the items
deleteItemsHandler(listObjResponse)
// Cleanup the Manifest iff defined
var deleteErr error
if nil != request.Manifest {
name := request.ManifestName
if name == "" {
name = DefaultManifestName
}
manifestDeleteParams := &awsv2S3.DeleteObjectInput{
Bucket: awsv2.String(request.DestBucket),
Key: awsv2.String(name),
}
_, deleteErr = svc.DeleteObject(context.Background(), manifestDeleteParams)
logger.Info().
Int("TotalDeletedCount", totalItemsDeleted).
Interface("S3Bucket", request.DestBucket).
Msg("Purged S3 Bucket")
}
return nil, deleteErr
}