-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
355 lines (315 loc) · 11.5 KB
/
index.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
'use strict';
const BbPromise = require('bluebird')
class InvokeCloudside {
constructor(serverless, options) {
this.serverless = serverless
this.options = options
this.commands = {
invoke: {
commands: {
cloudside: {
usage: 'Invoke function locally using cloudside resources',
lifecycleEvents: [
'loadCloudsideEnvVars',
'invoke',
],
options: {
function: {
usage: 'Name of the function',
shortcut: 'f',
required: true,
type: 'string',
},
cloudStage: {
usage: 'Stage to use for cloudside resources',
shortcut: 'S',
type: 'string',
},
stackName: {
usage: 'CloudFormation stack to use for cloudside resources',
shortcut: 'y',
type: 'string',
},
path: {
usage: 'Path to JSON or YAML file holding input data',
shortcut: 'p',
type: 'string',
},
data: {
usage: 'input data',
shortcut: 'd',
type: 'string',
},
raw: {
usage: 'Flag to pass input data as a raw string',
type: 'string',
},
context: {
usage: 'Context of the service',
type: 'string',
shortcut: 'c',
},
contextPath: {
usage: 'Path to JSON or YAML file holding context data',
type: 'string',
shortcut: 'x',
},
env: {
usage: 'Override environment variables. e.g. --env VAR1=val1 --env VAR2=val2',
type: 'string',
shortcut: 'e',
},
docker: {
usage: 'Flag to turn on docker use for node/python/ruby/java',
type: 'string'
},
'docker-arg': {
usage: 'Arguments to docker run command. e.g. --docker-arg "-p 9229:9229"',
type: 'string',
},
},
},
test: {
usage: 'NOT INSTALLED - A testing plugin must be installed to use "invoke test cloudside"',
commands: {
cloudside: {
usage: 'Invoke test(s) using cloudside resources',
lifecycleEvents: [
'loadCloudsideEnvVars',
'start'
],
options: {
cloudStage: {
usage: 'Stage to use for cloudside resources',
shortcut: 'S',
type: 'string',
},
stackName: {
usage: 'CloudFormation stack to use for cloudside resources',
shortcut: 'y',
type: 'string',
}
}
}
}
}
},
},
offline: {
lifecycleEvents: [
'checkInstall'
],
usage: 'NOT INSTALLED - This plugin must be installed to use "offline cloudside"',
commands: {
cloudside: {
usage: 'Simulates API Gateway to call your lambda functions offline using cloudside resources',
lifecycleEvents: [
'checkInstall',
'loadCloudsideEnvVars',
'start'
],
options: {
cloudStage: {
usage: 'Stage to use for cloudside resources',
shortcut: 'S',
type: 'string',
},
reloadHandler: {
usage: 'Enable serverless reload functionality',
shortcut: 'r',
type: 'boolean',
},
stackName: {
usage: 'CloudFormation stack to use for cloudside resources',
shortcut: 'y',
type: 'string',
}
}
}
}
}
};
this.hooks = {
'invoke:cloudside:loadCloudsideEnvVars': () => BbPromise.bind(this).then(this.loadCloudsideEnvVars),
'invoke:test:cloudside:loadCloudsideEnvVars': () => BbPromise.bind(this).then(this.loadCloudsideEnvVars),
'offline:cloudside:loadCloudsideEnvVars': () => BbPromise.bind(this).then(this.loadCloudsideEnvVars),
'after:invoke:cloudside:invoke': () => this.serverless.pluginManager.run(['invoke', 'local']),
'after:offline:cloudside:start': () => this.serverless.pluginManager.run(['offline', 'start']),
'offline:checkInstall': () => BbPromise.bind(this).then(this.checkInstall('serverless-offline')),
'offline:cloudside:checkInstall': () => BbPromise.bind(this).then(this.checkInstall('serverless-offline')),
'after:invoke:test:cloudside:start': () => this.serverless.pluginManager.run(['invoke', 'test']),
};
}
checkInstall(plugin) {
if (!this.serverless.service.plugins.includes(plugin)) {
throw Error(`You must install "${plugin}" to use the "offline cloudside" feature.\n\n You can install it by running "serverless plugin install --name ${plugin}"`)
}
return BbPromise.resolve()
}
getStackResources(result, params, options) {
return this.serverless.getProvider('aws')
.request('CloudFormation',
'listStackResources',
params,
options)
.then(res => {
result = [ ...result, ...res.StackResourceSummaries ]
if(res.NextToken) {
return this.getStackResources(result, { ...params, NextToken: res.NextToken }, options);
}
return result;
}).catch(e => {
console.log(e)
})
};
// Set environment variables for "invoke cloudside"
loadCloudsideEnvVars() {
// Get the stage (use the cloudstage option first, then stage option, then provider)
const stage = this.options.cloudStage ? this.options.cloudStage :
this.options.stage ? this.options.stage :
this.serverless.service.provider.stage
// Get the stack name (use provided stackName or fallback to service name)
const stackName = this.options.stackName ? this.options.stackName :
this.serverless.service.provider.stackName ?
this.serverless.service.provider.stackName :
`${this.serverless.service.service}-${stage}`
this.serverless.cli.log(`Loading cloudside resources for '${stackName}' stack.`)
if (!this.serverless.service.provider.environment) {
this.serverless.service.provider.environment = {}
}
this.serverless.service.provider.environment.IS_CLOUDSIDE = true
this.serverless.service.provider.environment.CLOUDSIDE_STACK = stackName
// Find all envs with CloudFormation Refs
let cloudsideVars = parseEnvs(this.serverless.service.provider.environment)
let functions = this.options.function ?
{ [this.options.function] : this.serverless.service.functions[this.options.function] }
: this.serverless.service.functions
Object.keys(functions).map(fn => {
if (this.serverless.service.functions[fn].environment) {
let vars = parseEnvs(this.serverless.service.functions[fn].environment,fn)
for (let key in vars) {
cloudsideVars[key] = cloudsideVars[key] ? cloudsideVars[key].concat(vars[key]) : vars[key]
}
}
})
// If references need resolving, call CF
if (Object.keys(cloudsideVars).length > 0) {
const options = { useCache: true }
const hander = (stackResources) => {
if (stackResources) {
// Loop through the returned StackResources
for (let i = 0; i < stackResources.length; i++) {
let resource = cloudsideVars[stackResources[i].LogicalResourceId]
// If the logicial id exists, add the PhysicalResourceId to the ENV
if (resource) {
for (let j = 0; j < resource.length; j++) {
let value = resource[j].type == 'Ref' ? stackResources[i].PhysicalResourceId
: buildCloudValue(stackResources[i],resource[j].type)
if (resource[j].fn) {
this.serverless.service.functions[resource[j].fn].environment[
resource[j].env
] = value
} else {
this.serverless.service.provider.environment[
resource[j].env
] = value
}
} // end for
// Remove the cloudside variable
delete(cloudsideVars[stackResources[i].LogicalResourceId])
} // end if
} // end for
} // end if StackResources
// Replace remaining variables with warning
Object.keys(cloudsideVars).map(x => {
for (let j = 0; j < cloudsideVars[x].length; j++) {
if (cloudsideVars[x][j].fn) {
this.serverless.service.functions[cloudsideVars[x][j].fn].environment[
cloudsideVars[x][j].env
] = '<RESOURCE NOT PUBLISHED>'
} else {
this.serverless.service.provider.environment[
cloudsideVars[x][j].env
] = '<RESOURCE NOT PUBLISHED>'
}
}
})
return true
}
return this.getStackResources([], { StackName: stackName }, options).then(hander);
} else {
return BbPromise.resolve()
}
}
}
// Parse the environment variables and return formatted mappings
const parseEnvs = (envs = {},fn) => Object.keys(envs).reduce((vars,key) => {
let logicalId,ref
if (envs[key].Ref) {
logicalId = envs[key].Ref
ref = { type: 'Ref', env: key, fn }
} else if (envs[key]['Fn::GetAtt']) {
logicalId = envs[key]['Fn::GetAtt'][0]
ref = { type: envs[key]['Fn::GetAtt'][1], env: key, fn }
} else {
return vars
}
vars[logicalId] = vars[logicalId] ?
vars[logicalId].concat([ref]) : [ref]
return vars
},{})
// Build the cloud value based on type
const buildCloudValue = (resource,type) => {
switch(type) {
case 'Arn':
return generateArn(resource)
default:
return '<FUNCTION NOT SUPPORTED>'
}
}
const getRdsResourceType = resourceType => {
switch(resourceType) {
case 'dbcluster':
return 'cluster'
case 'dbinstance':
return 'db'
default:
return null
}
}
// Generate the ARN based on service type
// TODO: add more service types or figure out a better way to do this
const generateArn = resource => {
let stack = resource.StackId.split(':').slice(0,5)
let resourceType = resource.ResourceType.split('::')
let serviceType = resourceType[1].toLowerCase()
stack[2] = serviceType
switch(serviceType) {
case 'sqs':
stack.push(resource.PhysicalResourceId.split('/').slice(-1))
break
case 'dynamodb':
case 'kinesis':
stack.push(resourceType[2].toLowerCase()+'/'+resource.PhysicalResourceId)
break
case 'rds':
const rdsResourceType = getRdsResourceType(resourceType[2].toLowerCase())
if (!rdsResourceType) {
return '<RDS RESOURCE NOT SUPPORTED>'
}
stack.push(rdsResourceType)
stack.push(resource.PhysicalResourceId)
break
case 'secretsmanager':
stack = resource.PhysicalResourceId.split('-').slice(0, -1).join('-').split(':')
break
case 's3':
stack.splice(3,5,'','')
stack.push(resource.PhysicalResourceId)
break
default:
return '<RESOURCE NOT SUPPORTED>'
}
return stack.join(':')
}
module.exports = InvokeCloudside