/
deploy.go
347 lines (297 loc) · 7.15 KB
/
deploy.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
package main
import "github.com/hopkinsth/lambda-phage/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/lambda"
import "github.com/hopkinsth/lambda-phage/Godeps/_workspace/src/github.com/aws/aws-sdk-go/service/s3"
import "github.com/hopkinsth/lambda-phage/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws"
import "github.com/hopkinsth/lambda-phage/Godeps/_workspace/src/github.com/aws/aws-sdk-go/aws/awserr"
import "github.com/hopkinsth/lambda-phage/Godeps/_workspace/src/github.com/tj/go-debug"
import "os"
import "io"
import "io/ioutil"
import "fmt"
import "bytes"
//import "github.com/aws/aws-sdk-go/aws"
import "github.com/hopkinsth/lambda-phage/Godeps/_workspace/src/github.com/spf13/cobra"
func init() {
dCmd := &cobra.Command{
Use: "deploy",
Short: "deploys your lambda function according to your config file or options provided",
RunE: deployCmd,
}
dCmd.Flags().Bool("skip-archive", false, "skip creating an archive (the `pkg` command)")
cmds = append(cmds, dCmd)
}
func deployCmd(c *cobra.Command, args []string) error {
d := &deployer{
cfg,
}
return d.deploy(c, args)
}
type deployer struct {
cfg *Config
}
func (d *deployer) deploy(c *cobra.Command, args []string) error {
debug := debug.Debug("cmd.deploy")
// must package first, so:
var err error
if d.cfg == nil {
return fmt.Errorf(
`No configuration file found, and you must have one to deploy!
Try running lambda-phage init before deploying.
`)
}
fmt.Printf("Beginning deploy of lambda function %s\n", *d.cfg.Name)
skipPkg, _ := c.Flags().GetBool("skip-archive")
if !skipPkg {
pkgEr := packager{
cfg,
}
err = pkgEr.pkg(c, args)
if err != nil {
return err
}
}
// should have written data to this file
binName := getArchiveName(c, d.cfg)
var iamRole *string
iamRole, err = cfg.getRoleArn()
if err != nil {
return err
}
code := &lambda.FunctionCode{}
// try getting s3 information
bucket, key := cfg.getS3Info(binName)
if bucket == nil || key == nil {
fmt.Printf("Will upload archive %s to Lambda\n", binName)
// if we couldn't get bucket or
// key info, let's upload the data
// ...soon
b, err := ioutil.ReadFile(binName)
if err != nil {
return err
}
code.ZipFile = b
} else {
fmt.Printf("Will upload archive %s to s3\n", binName)
code.S3Bucket = bucket
code.S3Key = key
err = d.uploadS3(binName, bucket, key)
if err != nil {
return err
}
}
debug("preparing for lambda API")
for _, region := range cfg.Regions {
fmt.Printf("Deploying lambda function for %s\n", *region)
l := lambda.New(
aws.NewConfig().
WithRegion(*region),
)
//just try creating the function now
_, err := l.CreateFunction(
&lambda.CreateFunctionInput{
Code: code,
FunctionName: cfg.Name,
Description: cfg.Description,
Handler: cfg.EntryPoint,
MemorySize: cfg.MemorySize,
Runtime: cfg.Runtime,
Timeout: cfg.Timeout,
Role: iamRole,
Publish: aws.Bool(true),
},
)
if err != nil {
if awe, ok := err.(awserr.Error); ok {
if awe.Code() == "ResourceConflictException" {
debug("function already exists, calling update")
err = d.updateLambda(l, code, iamRole)
} else {
return err
}
} else {
return err
}
} else {
// if the create function succeeded,
// we need to figure out the mapping
// info, etc
debug("function creation succeeded! ...we think")
}
if err != nil {
return err
}
fmt.Printf("Function %s deployed to region %s!\n", *cfg.Name, *region)
}
return nil
}
// updates function code, settings in AWS lambda
func (d *deployer) updateLambda(
l *lambda.Lambda,
code *lambda.FunctionCode,
iamRole *string,
) error {
cfg := d.cfg
_, err := l.UpdateFunctionConfiguration(
&lambda.UpdateFunctionConfigurationInput{
FunctionName: cfg.Name,
Description: cfg.Description,
Handler: cfg.EntryPoint,
MemorySize: cfg.MemorySize,
Role: iamRole,
Timeout: cfg.Timeout,
},
)
if err != nil {
return err
}
_, err = l.UpdateFunctionCode(
&lambda.UpdateFunctionCodeInput{
FunctionName: cfg.Name,
S3Bucket: code.S3Bucket,
S3Key: code.S3Key,
S3ObjectVersion: code.S3ObjectVersion,
ZipFile: code.ZipFile,
Publish: aws.Bool(true),
},
)
if err != nil {
return err
}
return nil
}
// should probably handle this in memory,
// but this fn will upload your file to s3
func (d *deployer) uploadS3(fName string, bucket, key *string) error {
cfg := d.cfg
debug := debug.Debug("uploadS3")
awscfg := aws.NewConfig().WithRegion(*cfg.Location.S3Region)
s := s3.New(awscfg)
f, err := os.Open(fName)
if err != nil {
return err
}
debug("opened file, beginning read")
st, err := f.Stat()
if err != nil {
return err
}
if st.Size() >= (1024 * 1024 * 5) {
// multipart if bigger than 5MiB
return uploadS3MPU(s, f, bucket, key)
} else {
_, err = s.PutObject(&s3.PutObjectInput{
Bucket: bucket,
Key: key,
Body: f,
})
if err != nil {
return err
}
}
return nil
}
// multipart upload
func uploadS3MPU(
s *s3.S3,
f *os.File,
bucket, key *string,
) error {
debug := debug.Debug("uploadS3MPU")
mpu := &s3.CreateMultipartUploadInput{
Bucket: bucket,
Key: key,
}
canceler := func(uploadId *string) {
debug("canceling upload")
_, err := s.AbortMultipartUpload(
&s3.AbortMultipartUploadInput{
Bucket: bucket,
Key: key,
UploadId: uploadId,
},
)
if err != nil {
fmt.Printf(
"WARNING: upload abort failed for upload ID %s",
*uploadId,
)
}
}
cr, err := s.CreateMultipartUpload(mpu)
if err != nil {
return err
}
debug("created multipart upload")
buf := new(bytes.Buffer)
bslice := make([]byte, 8096)
var pNum int64 = 1
parts := make([]*s3.CompletedPart, 0)
for {
n, err := f.Read(bslice)
isEOF := err != nil && err == io.EOF
if err != nil && !isEOF {
f.Close()
canceler(cr.UploadId)
return err
}
if isEOF {
debug("reached end of file")
// trim final content
bslice = bslice[:n]
}
buf.Write(bslice)
// drain buf on 1MiB of data
if buf.Len() >= (1024*1024*5) || isEOF {
debug("have file data, uploading chunk")
var err error
if buf.Len() > 0 {
var p *s3.UploadPartOutput
p, err = s.UploadPart(
&s3.UploadPartInput{
Bucket: bucket,
Key: key,
PartNumber: aws.Int64(pNum),
UploadId: cr.UploadId,
Body: bytes.NewReader(buf.Bytes()),
},
)
if err != nil {
// if uploading a part failed,
// cancel the whole upload...
f.Close()
canceler(cr.UploadId)
return err
}
parts = append(parts,
&s3.CompletedPart{
ETag: p.ETag,
PartNumber: aws.Int64(pNum),
},
)
}
pNum += 1
buf.Reset()
if isEOF {
f.Close()
debug("completing upload")
iput := &s3.CompleteMultipartUploadInput{
Bucket: bucket,
Key: key,
UploadId: cr.UploadId,
MultipartUpload: &s3.CompletedMultipartUpload{
Parts: parts,
},
}
_, err := s.CompleteMultipartUpload(
iput,
)
if err != nil {
canceler(cr.UploadId)
return err
}
break
}
}
}
return nil
}