forked from imjerrybao/apex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
function.go
456 lines (363 loc) · 10.1 KB
/
function.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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// Package function implements function-level operations.
package function
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/lambda"
"github.com/aws/aws-sdk-go/service/lambda/lambdaiface"
"github.com/dustin/go-humanize"
"github.com/jpillora/archive"
"gopkg.in/validator.v2"
"github.com/apex/apex/hooks"
"github.com/apex/apex/utils"
"github.com/apex/log"
)
// InvocationType determines how an invocation request is made.
type InvocationType string
// Invocation types.
const (
RequestResponse InvocationType = "RequestResponse"
Event = "Event"
DryRun = "DryRun"
)
// Current alias name.
const CurrentAlias = "current"
// InvokeError records an error from an invocation.
type InvokeError struct {
Message string `json:"errorMessage"`
Type string `json:"errorType"`
Stack []string `json:"stackTrace"`
Handled bool
}
// Error message.
func (e *InvokeError) Error() string {
return e.Message
}
// Config for a Lambda function.
type Config struct {
Description string `json:"description"`
Runtime string `json:"runtime" validate:"nonzero"`
Memory int64 `json:"memory" validate:"nonzero"`
Timeout int64 `json:"timeout" validate:"nonzero"`
Role string `json:"role" validate:"nonzero"`
Handler string `json:"handler" validate:"nonzero"`
Shim bool `json:"shim"`
Environment map[string]string `json:"environment"`
Hooks hooks.Hooks `json:"hooks"`
}
// Function represents a Lambda function, with configuration loaded
// from the "function.json" file on disk.
type Function struct {
Config
Name string
FunctionName string
Path string
Service lambdaiface.LambdaAPI
Log log.Interface
IgnoredPatterns []string
}
// Open the function.json file and prime the config.
func (f *Function) Open() error {
f.Log = f.Log.WithField("function", f.Name)
if f.Environment == nil {
f.Environment = make(map[string]string)
}
p, err := os.Open(filepath.Join(f.Path, "function.json"))
if err == nil {
if err := json.NewDecoder(p).Decode(&f.Config); err != nil {
return err
}
}
if err := f.hook(OpenHook); err != nil {
return err
}
if err := validator.Validate(&f.Config); err != nil {
return fmt.Errorf("error opening function %s: %s", f.Name, err.Error())
}
patterns, err := utils.ReadIgnoreFile(f.Path)
if err != nil {
return err
}
f.IgnoredPatterns = append(f.IgnoredPatterns, patterns...)
return nil
}
// Setenv sets environment variable `name` to `value`.
func (f *Function) Setenv(name, value string) {
f.Environment[name] = value
}
// Deploy code and then configuration.
func (f *Function) Deploy() error {
if err := f.DeployCode(); err != nil {
return err
}
return f.DeployConfig()
}
// DeployCode generates a zip and creates or updates the function.
func (f *Function) DeployCode() error {
f.Log.Info("deploying")
zip, err := f.BuildBytes()
if err != nil {
return err
}
if err := f.hook(DeployHook); err != nil {
return err
}
config, err := f.GetConfig()
if e, ok := err.(awserr.Error); ok {
if e.Code() == "ResourceNotFoundException" {
return f.Create(zip)
}
}
if err != nil {
return err
}
remoteHash := *config.Configuration.CodeSha256
localHash := utils.Sha256(zip)
if localHash == remoteHash {
f.Log.Info("unchanged")
return nil
}
f.Log.WithFields(log.Fields{
"local": localHash,
"remote": remoteHash,
}).Debug("changed")
return f.Update(zip)
}
// DeployConfig deploys changes to configuration.
func (f *Function) DeployConfig() error {
f.Log.Info("deploying config")
_, err := f.Service.UpdateFunctionConfiguration(&lambda.UpdateFunctionConfigurationInput{
FunctionName: &f.FunctionName,
MemorySize: &f.Memory,
Timeout: &f.Timeout,
Description: &f.Description,
Role: &f.Role,
Handler: &f.Handler,
})
return err
}
// Delete the function including all its versions
func (f *Function) Delete() error {
f.Log.Info("deleting")
_, err := f.Service.DeleteFunction(&lambda.DeleteFunctionInput{
FunctionName: &f.FunctionName,
})
return err
}
// GetConfig returns the function configuration.
func (f *Function) GetConfig() (*lambda.GetFunctionOutput, error) {
f.Log.Debug("fetching config")
return f.Service.GetFunction(&lambda.GetFunctionInput{
FunctionName: &f.FunctionName,
})
}
// Update the function with the given `zip`.
func (f *Function) Update(zip []byte) error {
f.Log.Info("updating function")
updated, err := f.Service.UpdateFunctionCode(&lambda.UpdateFunctionCodeInput{
FunctionName: &f.FunctionName,
Publish: aws.Bool(true),
ZipFile: zip,
})
if err != nil {
return err
}
f.Log.Info("updating alias")
_, err = f.Service.UpdateAlias(&lambda.UpdateAliasInput{
FunctionName: &f.FunctionName,
Name: aws.String(CurrentAlias),
FunctionVersion: updated.Version,
})
if err != nil {
return nil
}
f.Log.WithFields(log.Fields{
"version": *updated.Version,
"name": f.FunctionName,
}).Info("deployed")
return nil
}
// Create the function with the given `zip`.
func (f *Function) Create(zip []byte) error {
f.Log.Info("creating function")
created, err := f.Service.CreateFunction(&lambda.CreateFunctionInput{
FunctionName: &f.FunctionName,
Description: &f.Description,
MemorySize: &f.Memory,
Timeout: &f.Timeout,
Runtime: &f.Runtime,
Handler: &f.Handler,
Role: &f.Role,
Publish: aws.Bool(true),
Code: &lambda.FunctionCode{
ZipFile: zip,
},
})
if err != nil {
return err
}
f.Log.Info("creating alias")
_, err = f.Service.CreateAlias(&lambda.CreateAliasInput{
FunctionName: &f.FunctionName,
FunctionVersion: created.Version,
Name: aws.String(CurrentAlias),
})
if err != nil {
return nil
}
f.Log.WithFields(log.Fields{
"version": *created.Version,
"name": f.FunctionName,
}).Info("deployed")
return nil
}
// Invoke the remote Lambda function, returning the response and logs, if any.
func (f *Function) Invoke(event, context interface{}, kind InvocationType) (reply, logs io.Reader, err error) {
eventBytes, err := json.Marshal(event)
if err != nil {
return nil, nil, err
}
contextBytes, err := json.Marshal(context)
if err != nil {
return nil, nil, err
}
res, err := f.Service.Invoke(&lambda.InvokeInput{
ClientContext: aws.String(base64.StdEncoding.EncodeToString(contextBytes)),
FunctionName: &f.FunctionName,
InvocationType: aws.String(string(kind)),
LogType: aws.String("Tail"),
Qualifier: aws.String(CurrentAlias),
Payload: eventBytes,
})
if err != nil {
return nil, nil, err
}
if res.FunctionError != nil {
e := &InvokeError{
Handled: *res.FunctionError == "Handled",
}
if err := json.Unmarshal(res.Payload, e); err != nil {
return nil, nil, err
}
return nil, nil, e
}
if kind == Event {
return bytes.NewReader(nil), bytes.NewReader(nil), nil
}
logs = base64.NewDecoder(base64.StdEncoding, strings.NewReader(*res.LogResult))
reply = bytes.NewReader(res.Payload)
return reply, logs, nil
}
// Rollback the function to the previous.
func (f *Function) Rollback() error {
f.Log.Info("rolling back")
alias, err := f.Service.GetAlias(&lambda.GetAliasInput{
FunctionName: &f.FunctionName,
Name: aws.String(CurrentAlias),
})
if err != nil {
return err
}
f.Log.Infof("current version: %s", *alias.FunctionVersion)
list, err := f.Service.ListVersionsByFunction(&lambda.ListVersionsByFunctionInput{
FunctionName: &f.FunctionName,
})
if err != nil {
return err
}
versions := list.Versions[1:] // remove $LATEST
if len(versions) < 2 {
return errors.New("Can't rollback. Only one version deployed.")
}
latest := *versions[len(versions)-1].Version
prev := *versions[len(versions)-2].Version
rollback := latest
if *alias.FunctionVersion == latest {
rollback = prev
}
f.Log.Infof("rollback to version: %s", rollback)
_, err = f.Service.UpdateAlias(&lambda.UpdateAliasInput{
FunctionName: &f.FunctionName,
Name: aws.String(CurrentAlias),
FunctionVersion: &rollback,
})
return err
}
// RollbackVersion the function to the specified version.
func (f *Function) RollbackVersion(version string) error {
f.Log.Info("rolling back")
alias, err := f.Service.GetAlias(&lambda.GetAliasInput{
FunctionName: &f.FunctionName,
Name: aws.String(CurrentAlias),
})
if err != nil {
return err
}
f.Log.Infof("current version: %s", *alias.FunctionVersion)
if version == *alias.FunctionVersion {
return errors.New("Specified version currently deployed.")
}
_, err = f.Service.UpdateAlias(&lambda.UpdateAliasInput{
FunctionName: &f.FunctionName,
Name: aws.String(CurrentAlias),
FunctionVersion: &version,
})
return err
}
// BuildBytes returns the generated zip as bytes.
func (f *Function) BuildBytes() ([]byte, error) {
r, err := f.Build()
if err != nil {
return nil, err
}
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
f.Log.Infof("created build (%s)", humanize.Bytes(uint64(len(b))))
return b, nil
}
// Build returns the zipped contents of the function.
func (f *Function) Build() (io.Reader, error) {
f.Log.Debugf("creating build")
if err := f.hook(BuildHook); err != nil {
return nil, err
}
buf := new(bytes.Buffer)
zip := archive.NewZipWriter(buf)
files, err := utils.LoadFiles(f.Path, f.IgnoredPatterns)
if err != nil {
return nil, err
}
for _, path := range files {
f.Log.WithField("file", path).Debug("add file to zip")
file, err := os.Open(filepath.Join(f.Path, path))
if err != nil {
return nil, err
}
if err := zip.AddFile(path, file); err != nil {
return nil, err
}
if err := file.Close(); err != nil {
return nil, err
}
}
if err := zip.Close(); err != nil {
return nil, err
}
return buf, nil
}
// Clean invokes the CleanHook, useful for removing build artifacts and so on.
func (f *Function) Clean() error {
return f.hook(CleanHook)
}