-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathplugin.go
392 lines (344 loc) · 10.2 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
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
package main
import (
"context"
"errors"
"log"
"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/aws/credentials"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/lambda"
"github.com/gookit/goutil/dump"
"github.com/mholt/archiver/v3"
)
type (
// Config for the plugin.
Config struct {
Region string
AccessKey string
SecretKey string
Profile string
FunctionName string
ReversionID string
S3Bucket string
S3Key string
S3ObjectVersion string
DryRun bool
ZipFile string
Source []string
Debug bool
Publish bool
MemorySize int64
Timeout int64
Handler string
Role string
Runtime string
Environment []string
ImageURI string
Subnets []string
SecurityGroups []string
Description string
Layers []string
SessionToken string
TracingMode string
MaxAttempts int
Architectures []string
IP6DualStack bool
}
// Commit information.
Commit struct {
Sha string
Author string
}
// Plugin values.
Plugin struct {
Config Config
Commit Commit
}
)
func getEnvironment(envs []string) map[string]string {
output := make(map[string]string)
for _, e := range envs {
pair := strings.SplitN(e, "=", 2)
if len(pair) != 2 {
continue
}
output[pair[0]] = pair[1]
}
return output
}
func (p Plugin) loadEnvironment(envs []string) *lambda.Environment {
return &lambda.Environment{
Variables: aws.StringMap(getEnvironment(envs)),
}
}
// Exec executes the plugin.
func (p Plugin) Exec(ctx context.Context) error { //nolint:gocyclo
p.dump(p.Config)
if p.Config.FunctionName == "" {
return errors.New("missing lambda function name")
}
sources := trimValues(p.Config.Source)
if p.Config.S3Bucket == "" &&
p.Config.S3Key == "" &&
len(sources) == 0 &&
p.Config.ZipFile == "" &&
p.Config.ImageURI == "" {
return errors.New("missing zip source or s3 bucket/key or image uri")
}
// Create Lambda service client
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
config := &aws.Config{
Region: aws.String(p.Config.Region),
}
if p.Config.Profile != "" {
config.Credentials = credentials.NewSharedCredentials("", p.Config.Profile)
}
if p.Config.AccessKey != "" && p.Config.SecretKey != "" {
config.Credentials = credentials.NewStaticCredentials(p.Config.AccessKey, p.Config.SecretKey, p.Config.SessionToken)
}
if p.Config.DryRun {
p.Config.Publish = false
} else {
p.Config.Publish = true
}
input := &lambda.UpdateFunctionCodeInput{}
input.SetDryRun(p.Config.DryRun)
input.SetFunctionName(p.Config.FunctionName)
input.SetPublish(p.Config.Publish)
if p.Config.ImageURI != "" {
input.SetImageUri(p.Config.ImageURI)
}
if p.Config.ReversionID != "" {
input.SetRevisionId(p.Config.ReversionID)
}
if p.Config.S3Bucket != "" && p.Config.S3Key != "" {
input.SetS3Key(p.Config.S3Key)
input.SetS3Bucket(p.Config.S3Bucket)
if p.Config.S3ObjectVersion != "" {
input.SetS3ObjectVersion(p.Config.S3ObjectVersion)
}
}
//
if len(p.Config.Architectures) != 0 {
input.SetArchitectures(aws.StringSlice(p.Config.Architectures))
}
if len(sources) != 0 {
files := globList(sources)
path := os.TempDir() + "/output.zip"
zip := archiver.NewZip()
if len(files) != 0 {
if err := zip.Archive(files, path); err != nil {
return err
}
p.Config.ZipFile = path
}
}
if p.Config.ZipFile != "" {
contents, err := os.ReadFile(p.Config.ZipFile)
if err != nil {
return err
}
input.SetZipFile(contents)
}
isUpdateConfig := false
cfg := &lambda.UpdateFunctionConfigurationInput{}
cfg.SetFunctionName(p.Config.FunctionName)
if p.Config.MemorySize > 0 {
isUpdateConfig = true
cfg.SetMemorySize(p.Config.MemorySize)
}
if p.Config.Timeout > 0 {
isUpdateConfig = true
cfg.SetTimeout(p.Config.Timeout)
}
if len(p.Config.Handler) > 0 {
isUpdateConfig = true
cfg.SetHandler(p.Config.Handler)
}
if len(p.Config.Role) > 0 {
isUpdateConfig = true
cfg.SetRole(p.Config.Role)
}
if len(p.Config.Runtime) > 0 {
isUpdateConfig = true
cfg.SetRuntime(p.Config.Runtime)
}
if p.Config.Description != "" {
isUpdateConfig = true
cfg.SetDescription(p.Config.Description)
}
if len(p.Config.Layers) > 0 {
isUpdateConfig = true
cfg.SetLayers(aws.StringSlice(p.Config.Layers))
}
envs := trimValues(p.Config.Environment)
if len(envs) > 0 {
isUpdateConfig = true
cfg.SetEnvironment(p.loadEnvironment(envs))
}
subnets := trimValues(p.Config.Subnets)
securityGroups := trimValues(p.Config.SecurityGroups)
if len(subnets) > 0 || len(securityGroups) > 0 {
isUpdateConfig = true
cfg.SetVpcConfig(&lambda.VpcConfig{
Ipv6AllowedForDualStack: aws.Bool(p.Config.IP6DualStack),
SubnetIds: aws.StringSlice(subnets),
SecurityGroupIds: aws.StringSlice(securityGroups),
})
}
if p.Config.TracingMode != "" {
isUpdateConfig = true
cfg.SetTracingConfig(&lambda.TracingConfig{
Mode: aws.String(p.Config.TracingMode),
})
}
svc := lambda.New(sess, config)
if isUpdateConfig {
// UpdateFunctionConfiguration API operation for AWS Lambda.
log.Println("Update function configuration ...")
if err := p.checkStatus(svc); err != nil {
return err
}
lambdaConfig, err := svc.UpdateFunctionConfigurationWithContext(ctx, cfg)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case lambda.ErrCodeServiceException:
log.Println(lambda.ErrCodeServiceException, aerr.Error())
case lambda.ErrCodeResourceNotFoundException:
log.Println(lambda.ErrCodeResourceNotFoundException, aerr.Error())
case lambda.ErrCodeInvalidParameterValueException:
log.Println(lambda.ErrCodeInvalidParameterValueException, aerr.Error())
case lambda.ErrCodeTooManyRequestsException:
log.Println(lambda.ErrCodeTooManyRequestsException, aerr.Error())
case lambda.ErrCodeResourceConflictException:
log.Println(lambda.ErrCodeResourceConflictException, aerr.Error())
case lambda.ErrCodePreconditionFailedException:
log.Println(lambda.ErrCodePreconditionFailedException, aerr.Error())
default:
log.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
log.Println(err.Error())
}
return err
}
p.dump(lambdaConfig)
}
log.Println("Update function code ...")
if err := p.checkStatus(svc); err != nil {
return err
}
lambdaConfig, err := svc.UpdateFunctionCodeWithContext(ctx, input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
case lambda.ErrCodeServiceException:
log.Println(lambda.ErrCodeServiceException, aerr.Error())
case lambda.ErrCodeResourceNotFoundException:
log.Println(lambda.ErrCodeResourceNotFoundException, aerr.Error())
case lambda.ErrCodeInvalidParameterValueException:
log.Println(lambda.ErrCodeInvalidParameterValueException, aerr.Error())
case lambda.ErrCodeTooManyRequestsException:
log.Println(lambda.ErrCodeTooManyRequestsException, aerr.Error())
case lambda.ErrCodeCodeStorageExceededException:
log.Println(lambda.ErrCodeCodeStorageExceededException, aerr.Error())
case lambda.ErrCodeResourceConflictException:
log.Println(lambda.ErrCodeResourceConflictException, aerr.Error())
case lambda.ErrCodeResourceNotReadyException:
log.Println(lambda.ErrCodeResourceNotReadyException, aerr.Error())
default:
log.Println(aerr.Error())
}
} else {
// Print the error, cast err to awserr.Error to get the Code and
// Message from an error.
log.Println(err.Error())
}
return err
}
p.dump(lambdaConfig)
return nil
}
func (p *Plugin) checkStatus(svc *lambda.Lambda) error {
// Check Lambda function states
// see https://docs.aws.amazon.com/lambda/latest/dg/functions-states.html
lambdaConfig, err := svc.GetFunctionConfiguration(&lambda.GetFunctionConfigurationInput{
FunctionName: aws.String(p.Config.FunctionName),
})
if err != nil {
return err
}
log.Println("Current State:", aws.StringValue(lambdaConfig.State))
if aws.StringValue(lambdaConfig.State) != lambda.StateActive {
log.Println("Current State Reason:", aws.StringValue(lambdaConfig.StateReason))
log.Println("Current State Reason Code:", aws.StringValue(lambdaConfig.StateReasonCode))
log.Println("Waiting for Lambda function states to be active...")
if err := svc.WaitUntilFunctionActiveV2WithContext(
aws.BackgroundContext(),
&lambda.GetFunctionInput{
FunctionName: aws.String(p.Config.FunctionName),
},
request.WithWaiterMaxAttempts(p.Config.MaxAttempts),
); err != nil {
log.Println(err.Error())
return err
}
}
log.Println("Last Update Status:", aws.StringValue(lambdaConfig.LastUpdateStatus))
if aws.StringValue(lambdaConfig.LastUpdateStatus) != lambda.LastUpdateStatusSuccessful {
log.Println("Last Update Status Reason:", aws.StringValue(lambdaConfig.LastUpdateStatusReason))
log.Println("Last Update Status ReasonCode:", aws.StringValue(lambdaConfig.LastUpdateStatusReasonCode))
log.Println("Waiting for Last Update Status to be successful ...")
if err := svc.WaitUntilFunctionUpdatedV2WithContext(
aws.BackgroundContext(),
&lambda.GetFunctionInput{
FunctionName: aws.String(p.Config.FunctionName),
},
request.WithWaiterMaxAttempts(p.Config.MaxAttempts),
); err != nil {
log.Println(err.Error())
return err
}
}
return nil
}
func (p *Plugin) dump(val ...any) {
if !p.Config.Debug {
return
}
dump.P(val)
}
func trimValues(keys []string) []string {
var newKeys []string
for _, value := range keys {
value = strings.TrimSpace(value)
if len(value) == 0 {
continue
}
newKeys = append(newKeys, value)
}
return newKeys
}
func globList(paths []string) []string {
var newPaths []string
for _, pattern := range paths {
pattern = strings.Trim(pattern, " ")
matches, err := filepath.Glob(pattern)
if err != nil {
log.Printf("Glob error for %q: %s\n", pattern, err)
continue
}
newPaths = append(newPaths, matches...)
}
return newPaths
}