forked from serverless-components/aws-lambda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
261 lines (225 loc) · 5.96 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
const { tmpdir } = require('os')
const path = require('path')
const archiver = require('archiver')
const globby = require('globby')
const { contains, isNil, last, split, equals, not, pick } = require('ramda')
const { readFile, createReadStream, createWriteStream } = require('fs-extra')
const { utils } = require('@serverless/core')
const VALID_FORMATS = ['zip', 'tar']
const isValidFormat = (format) => contains(format, VALID_FORMATS)
const packDir = async (inputDirPath, outputFilePath, include = [], exclude = [], prefix) => {
const format = last(split('.', outputFilePath))
if (!isValidFormat(format)) {
throw new Error('Please provide a valid format. Either a "zip" or a "tar"')
}
const patterns = ['**']
if (!isNil(exclude)) {
exclude.forEach((excludedItem) => patterns.push(`!${excludedItem}`))
}
const files = (await globby(patterns, { cwd: inputDirPath, dot: true }))
.sort() // we must sort to ensure correct hash
.map((file) => ({
input: path.join(inputDirPath, file),
output: prefix ? path.join(prefix, file) : file
}))
return new Promise((resolve, reject) => {
const output = createWriteStream(outputFilePath)
const archive = archiver(format, {
zlib: { level: 9 }
})
output.on('open', () => {
archive.pipe(output)
// we must set the date to ensure correct hash
files.forEach((file) =>
archive.append(createReadStream(file.input), { name: file.output, date: new Date(0) })
)
if (!isNil(include)) {
include.forEach((file) => {
const stream = createReadStream(file)
archive.append(stream, { name: path.basename(file), date: new Date(0) })
})
}
archive.finalize()
})
archive.on('error', (err) => reject(err))
output.on('close', () => resolve(outputFilePath))
})
}
const getAccountId = async (aws) => {
const STS = new aws.STS()
const res = await STS.getCallerIdentity({}).promise()
return res.Account
}
const createLambda = async ({
lambda,
name,
handler,
memory,
timeout,
runtime,
env,
description,
zipPath,
bucket,
role,
layer
}) => {
const params = {
FunctionName: name,
Code: {},
Description: description,
Handler: handler,
MemorySize: memory,
Publish: true,
Role: role.arn,
Runtime: runtime,
Timeout: timeout,
Environment: {
Variables: env
}
}
if (layer && layer.arn) {
params.Layers = [layer.arn]
}
if (bucket) {
params.Code.S3Bucket = bucket
params.Code.S3Key = path.basename(zipPath)
} else {
params.Code.ZipFile = await readFile(zipPath)
}
const res = await lambda.createFunction(params).promise()
return { arn: res.FunctionArn, hash: res.CodeSha256 }
}
const updateLambdaConfig = async ({
lambda,
name,
handler,
memory,
timeout,
runtime,
env,
description,
role,
layer
}) => {
const functionConfigParams = {
FunctionName: name,
Description: description,
Handler: handler,
MemorySize: memory,
Role: role.arn,
Runtime: runtime,
Timeout: timeout,
Environment: {
Variables: env
}
}
if (layer && layer.arn) {
functionConfigParams.Layers = [layer.arn]
}
const res = await lambda.updateFunctionConfiguration(functionConfigParams).promise()
return { arn: res.FunctionArn, hash: res.CodeSha256 }
}
const updateLambdaCode = async ({ lambda, name, zipPath, bucket }) => {
const functionCodeParams = {
FunctionName: name,
Publish: true
}
if (bucket) {
functionCodeParams.S3Bucket = bucket
functionCodeParams.S3Key = path.basename(zipPath)
} else {
functionCodeParams.ZipFile = await readFile(zipPath)
}
const res = await lambda.updateFunctionCode(functionCodeParams).promise()
return res.FunctionArn
}
const getLambda = async ({ lambda, name }) => {
try {
const res = await lambda
.getFunctionConfiguration({
FunctionName: name
})
.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
}
} catch (e) {
if (e.code === 'ResourceNotFoundException') {
return null
}
throw e
}
}
const deleteLambda = async ({ lambda, name }) => {
try {
const params = { FunctionName: name }
await lambda.deleteFunction(params).promise()
} catch (error) {
if (error.code !== 'ResourceNotFoundException') {
throw error
}
}
}
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'
}
]
}
}
const configChanged = (prevLambda, lambda) => {
const keys = ['description', 'runtime', 'role', 'handler', 'memory', 'timeout', 'env', 'hash']
const inputs = pick(keys, lambda)
inputs.role = { arn: inputs.role.arn } // remove other inputs.role component outputs
const prevInputs = pick(keys, prevLambda)
return not(equals(inputs, prevInputs))
}
const pack = async (code, shims = [], packDeps = true) => {
if (utils.isArchivePath(code)) {
return path.resolve(code)
}
let exclude = []
if (!packDeps) {
exclude = ['node_modules/**']
}
const outputFilePath = path.join(
tmpdir(),
`${Math.random()
.toString(36)
.substring(6)}.zip`
)
return packDir(code, outputFilePath, shims, exclude)
}
module.exports = {
createLambda,
updateLambdaCode,
updateLambdaConfig,
getLambda,
deleteLambda,
getPolicy,
getAccountId,
configChanged,
pack
}