-
Notifications
You must be signed in to change notification settings - Fork 44
/
Copy pathutils.js
591 lines (531 loc) · 15.6 KB
/
utils.js
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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
const https = require('https')
const AWS = require('@serverless/aws-sdk-extra')
const { equals, not, pick } = require('ramda')
const { readFile } = require('fs-extra')
const agent = new https.Agent({
keepAlive: true
})
/**
* Sleep
* @param {*} wait
*/
const sleep = async (wait) => new Promise((resolve) => setTimeout(() => resolve(), wait))
/**
* Generate a random ID
*/
const randomId = Math.random()
.toString(36)
.substring(6)
/**
* Get AWS SDK Clients
* @param {*} credentials
* @param {*} region
*/
const getClients = (credentials = {}, region) => {
AWS.config.update({
httpOptions: {
agent
}
})
const extras = new AWS.Extras({ credentials, region })
const iam = new AWS.IAM({ credentials, region })
const lambda = new AWS.Lambda({ credentials, region })
const sts = new AWS.STS({ credentials, region })
return { iam, lambda, extras, sts }
}
/**
* Prepare inputs
* @param {*} inputs
* @param {*} instance
*/
const prepareInputs = (inputs, instance) => {
return {
name: inputs.name || instance.state.name || `${instance.name}-${instance.stage}-${randomId}`,
roleName: inputs.roleName,
description:
inputs.description ||
`An AWS Lambda function from the AWS Lambda Serverless Framework Component. Name: "${instance.name}" Stage: "${instance.stage}"`,
memory: inputs.memory || 1028,
timeout: inputs.timeout || 10,
src: inputs.src || null,
handler: inputs.handler || 'handler.handler',
runtime: 'nodejs12.x',
env: inputs.env || {},
region: inputs.region || 'us-east-1',
layers: inputs.layers || [],
securityGroupIds: inputs.vpcConfig ? inputs.vpcConfig.securityGroupIds : false,
subnetIds: inputs.vpcConfig ? inputs.vpcConfig.subnetIds : false,
retry: inputs.retry || 0,
provisionedConcurrency: inputs.provisionedConcurrency || 0,
aliasName: (inputs.alias && inputs.alias.name) || 'provisioned'
}
}
/*
* Ensure the provided IAM Role or default IAM Role exists
*
* @param ${instance} instance - the component instance
* @param ${object} inputs - the component inputs
* @param ${object} clients - the aws clients object
*/
const createOrUpdateFunctionRole = async (instance, inputs, clients) => {
// Verify existing role, either provided or the previously created default role...
if (inputs.roleName) {
console.log(
`Verifying the provided IAM Role with the name: ${inputs.roleName} in the inputs exists...`
)
const userRole = await clients.extras.getRole({ roleName: inputs.roleName })
const userRoleArn = userRole && userRole.Role && userRole.Role.Arn ? userRole.Role.Arn : null // Don't save user provided role to state, always reference it as an input, in case it changes
// If user role exists, save it to state so it can be used for the create/update lambda logic later
if (userRoleArn) {
console.log(`The provided IAM Role with the name: ${inputs.roleName} in the inputs exists.`)
instance.state.userRoleArn = userRoleArn
// Save AWS Account ID by fetching the role ID
// TODO: This may not work with cross-account roles.
instance.state.awsAccountId = instance.state.userRoleArn.split(':')[4]
// Be sure to delete defaultLambdaRoleArn data, if it exists
if (instance.state.defaultLambdaRoleArn) {
delete instance.state.defaultLambdaRoleArn
}
} else {
throw new Error(`The provided IAM Role with the name: ${inputs.roleName} could not be found.`)
}
} else {
// Create a default role with basic Lambda permissions
const defaultLambdaRoleName = `${inputs.name}-lambda-role`
console.log(
`IAM Role not found. Creating or updating a default role with the name: ${defaultLambdaRoleName}`
)
const result = await clients.extras.deployRole({
roleName: defaultLambdaRoleName,
service: ['lambda.amazonaws.com'],
policy: 'arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole'
})
instance.state.defaultLambdaRoleName = defaultLambdaRoleName
instance.state.defaultLambdaRoleArn = result.roleArn
instance.state.awsAccountId = instance.state.defaultLambdaRoleArn.split(':')[4]
// Be sure to delete userRole data, if it exists
if (instance.state.userRoleArn) {
delete instance.state.userRoleArn
}
console.log(
`Default Lambda IAM Role created or updated with ARN ${instance.state.defaultLambdaRoleArn}`
)
}
}
/*
* Ensure the Meta IAM Role exists
*/
const createOrUpdateMetaRole = async (instance, inputs, clients, serverlessAccountId) => {
// Create or update Meta Role for monitoring and more, if option is enabled. It's enabled by default.
if (inputs.monitoring || typeof inputs.monitoring === 'undefined') {
console.log('Creating or updating the meta IAM Role...')
const roleName = `${instance.name}-meta-role`
const assumeRolePolicyDocument = {
Version: '2012-10-17',
Statement: {
Effect: 'Allow',
Principal: {
AWS: `arn:aws:iam::${serverlessAccountId}:root` // Serverless's Components account
},
Action: 'sts:AssumeRole'
}
}
// Create a policy that only can access APIGateway and Lambda metrics, logs from CloudWatch...
const policy = {
Version: '2012-10-17',
Statement: [
{
Effect: 'Allow',
Resource: '*',
Action: [
'cloudwatch:Describe*',
'cloudwatch:Get*',
'cloudwatch:List*',
'logs:Get*',
'logs:List*',
'logs:Describe*',
'logs:TestMetricFilter',
'logs:FilterLogEvents'
]
// TODO: Finish this. Haven't been able to get this to work. Perhaps there is a missing service (Cloudfront?)
// Condition: {
// StringEquals: {
// 'cloudwatch:namespace': [
// 'AWS/ApiGateway',
// 'AWS/Lambda'
// ]
// }
// }
}
]
}
const roleDescription = `The Meta Role for the Serverless Framework App: ${instance.name} Stage: ${instance.stage}`
const result = await clients.extras.deployRole({
roleName,
roleDescription,
policy,
assumeRolePolicyDocument
})
instance.state.metaRoleName = roleName
instance.state.metaRoleArn = result.roleArn
console.log(`Meta IAM Role created or updated with ARN ${instance.state.metaRoleArn}`)
}
}
/**
* Create a new lambda function
* @param {*} lambda
* @param {*} config
*/
const createLambdaFunction = async (instance, lambda, inputs) => {
const params = {
FunctionName: inputs.name,
Code: {},
Description: inputs.description,
Handler: inputs.handler,
MemorySize: inputs.memory,
Publish: true,
Role: instance.state.userRoleArn || instance.state.defaultLambdaRoleArn,
Runtime: inputs.runtime,
Timeout: inputs.timeout,
Layers: inputs.layers,
Environment: {
Variables: inputs.env
},
...(inputs.securityGroupIds && {
VpcConfig: {
SecurityGroupIds: inputs.securityGroupIds,
SubnetIds: inputs.subnetIds
}
})
}
params.Code.ZipFile = await readFile(inputs.src)
try {
const res = await lambda.createFunction(params).promise()
return { arn: res.FunctionArn, hash: res.CodeSha256, version: res.Version }
} catch (e) {
if (e.message.includes(`The role defined for the function cannot be assumed by Lambda`)) {
// we need to wait after the role is created before it can be assumed
await sleep(5000)
return await createLambdaFunction(instance, lambda, inputs)
}
throw e
}
}
/**
* Update Lambda configuration
* @param {*} lambda
* @param {*} config
*/
const updateLambdaFunctionConfig = async (instance, lambda, inputs) => {
const functionConfigParams = {
FunctionName: inputs.name,
Description: inputs.description,
Handler: inputs.handler,
MemorySize: inputs.memory,
Role: instance.state.userRoleArn || instance.state.defaultLambdaRoleArn,
Runtime: inputs.runtime,
Timeout: inputs.timeout,
Layers: inputs.layers,
Environment: {
Variables: inputs.env
},
...(inputs.securityGroupIds
? {
VpcConfig: {
SecurityGroupIds: inputs.securityGroupIds,
SubnetIds: inputs.subnetIds
}
}
: {
VpcConfig: {
SecurityGroupIds: [],
SubnetIds: []
}
})
}
const res = await lambda.updateFunctionConfiguration(functionConfigParams).promise()
// update retry config
await lambda
.putFunctionEventInvokeConfig({
FunctionName: inputs.name,
MaximumRetryAttempts: inputs.retry
})
.promise()
return { arn: res.FunctionArn, hash: res.CodeSha256 }
}
/**
* Update Lambda function code
* @param {*} lambda
* @param {*} config
*/
const updateLambdaFunctionCode = async (lambda, inputs) => {
const functionCodeParams = {
FunctionName: inputs.name,
Publish: true
}
functionCodeParams.ZipFile = await readFile(inputs.src)
const res = await lambda.updateFunctionCode(functionCodeParams).promise()
return { arn: res.FunctionArn, hash: res.CodeSha256, version: res.Version }
}
/**
* Get Lambda Alias
* @param {*} lambda
* @param {*} inputs
*/
const getLambdaAlias = async (lambda, inputs) => {
try {
const res = await lambda
.getAlias({
FunctionName: inputs.name,
Name: inputs.aliasName
})
.promise()
return {
name: res.Name,
description: res.Description,
arn: res.AliasArn,
resourceId: res.ResourceId,
routingConfig: res.RoutingConfig
}
} catch (e) {
if (e.code === 'ResourceNotFoundException') {
return null
}
throw e
}
}
/**
* Create a Lambda Alias
* @param {*} lambda
* @param {*} inputs
*/
const createLambdaAlias = async (lambda, inputs) => {
const params = {
FunctionName: inputs.name,
FunctionVersion: inputs.version,
Name: inputs.aliasName
}
const res = await lambda.createAlias(params).promise()
return { name: res.Name, arn: res.AliasArn }
}
/**
* Update a Lambda Alias
* @param {*} lambda
* @param {*} inputs
*/
const updateLambdaAlias = async (lambda, inputs) => {
const params = {
FunctionName: inputs.name,
FunctionVersion: inputs.version,
Name: inputs.aliasName
}
const res = await lambda.updateAlias(params).promise()
return { name: res.Name, arn: res.AliasArn }
}
/**
* Delete Lambda Alias, provisioned concurrency settings will be deleted together
* @param {*} lambda
* @param {*} inputs
*/
const deleteLambdaAlias = async (lambda, inputs) => {
const params = {
FunctionName: inputs.name,
Name: inputs.aliasName
}
const res = await lambda.deleteAlias(params).promise()
}
/**
* Update provisioned concurrency configurations
* @param {*} lambda
* @param {*} inputs
*/
const updateProvisionedConcurrencyConfig = async (lambda, inputs) => {
const params = {
FunctionName: inputs.name,
ProvisionedConcurrentExecutions: inputs.provisionedConcurrency,
Qualifier: inputs.aliasName
}
const res = await lambda.putProvisionedConcurrencyConfig(params).promise()
return {
allocated: res.AllocatedProvisionedConcurrentExecutions,
requested: res.RequestedProvisionedConcurrentExecutions
}
}
/**
* Get Lambda Function
* @param {*} lambda
* @param {*} functionName
*/
const getLambdaFunction = async (lambda, functionName) => {
try {
const res = await lambda
.getFunctionConfiguration({
FunctionName: functionName
})
.promise()
return {
name: res.FunctionName,
description: res.Description,
timeout: res.Timeout,
runtime: res.Runtime,
role: {
arn: res.Role
},
handler: res.Handler,
memory: res.MemorySize,
hash: res.CodeSha256,
env: res.Environment ? res.Environment.Variables : {},
arn: res.FunctionArn,
securityGroupIds: res.VpcConfig ? res.VpcConfig.SecurityGroupIds : false,
subnetIds: res.VpcConfig ? res.VpcConfig.SubnetIds : false
}
} catch (e) {
if (e.code === 'ResourceNotFoundException') {
return null
}
throw e
}
}
/**
* Delete Lambda function
* @param {*} param0
*/
const deleteLambdaFunction = async (lambda, functionName) => {
try {
const params = { FunctionName: functionName }
await lambda.deleteFunction(params).promise()
} catch (error) {
console.log(error)
if (error.code !== 'ResourceNotFoundException') {
throw error
}
}
}
/**
* Get AWS IAM role policy
* @param {*} param0
*/
const getPolicy = async ({ name, region, accountId }) => {
return {
Version: '2012-10-17',
Statement: [
{
Action: ['logs:CreateLogStream'],
Resource: [`arn:aws:logs:${region}:${accountId}:log-group:/aws/lambda/${name}:*`],
Effect: 'Allow'
},
{
Action: ['logs:PutLogEvents'],
Resource: [`arn:aws:logs:${region}:${accountId}:log-group:/aws/lambda/${name}:*:*`],
Effect: 'Allow'
}
]
}
}
/**
* Detect if inputs have changed
* @param {*} prevLambda
* @param {*} lambda
*/
const inputsChanged = (prevLambda, lambda) => {
const keys = [
'description',
'runtime',
'roleArn',
'handler',
'memory',
'timeout',
'env',
'hash',
'securityGroupIds',
'subnetIds',
'provisionedConcurrency'
]
const inputs = pick(keys, lambda)
const prevInputs = pick(keys, prevLambda)
return not(equals(inputs, prevInputs))
}
/*
* Removes the Function & Meta Roles from aws according to the provided config
*
* @param ${object} clients - an object containing aws sdk clients
* @param ${object} config - the component config
*/
const removeAllRoles = async (instance, clients) => {
// Delete Function Role
if (instance.state.defaultLambdaRoleName) {
console.log('Deleting the default Function Role...')
await clients.extras.removeRole({
roleName: instance.state.defaultLambdaRoleName
})
}
// Delete Meta Role
if (instance.state.metaRoleName) {
console.log('Deleting the Meta Role...')
await clients.extras.removeRole({
roleName: instance.state.metaRoleName
})
}
}
/**
* Get metrics from cloudwatch
* @param {*} clients
* @param {*} rangeStart MUST be a moment() object
* @param {*} rangeEnd MUST be a moment() object
*/
const getMetrics = async (region, metaRoleArn, functionName, rangeStart, rangeEnd) => {
/**
* Create AWS STS Token via the meta role that is deployed with the Express Component
*/
// Assume Role
const assumeParams = {}
assumeParams.RoleSessionName = `session${Date.now()}`
assumeParams.RoleArn = metaRoleArn
assumeParams.DurationSeconds = 900
const sts = new AWS.STS({ region })
const resAssume = await sts.assumeRole(assumeParams).promise()
const roleCreds = {}
roleCreds.accessKeyId = resAssume.Credentials.AccessKeyId
roleCreds.secretAccessKey = resAssume.Credentials.SecretAccessKey
roleCreds.sessionToken = resAssume.Credentials.SessionToken
/**
* Instantiate a new Extras instance w/ the temporary credentials
*/
const extras = new AWS.Extras({
credentials: roleCreds,
region
})
const resources = [
{
type: 'aws_lambda',
functionName
}
]
return await extras.getMetrics({
rangeStart,
rangeEnd,
resources
})
}
/**
* Exports
*/
module.exports = {
prepareInputs,
getClients,
createOrUpdateFunctionRole,
createOrUpdateMetaRole,
createLambdaFunction,
updateLambdaFunctionCode,
updateLambdaFunctionConfig,
getLambdaFunction,
getLambdaAlias,
createLambdaAlias,
updateLambdaAlias,
deleteLambdaAlias,
updateProvisionedConcurrencyConfig,
inputsChanged,
deleteLambdaFunction,
removeAllRoles,
getMetrics
}