forked from serverless/serverless
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctionRun.js
More file actions
258 lines (212 loc) · 7.59 KB
/
FunctionRun.js
File metadata and controls
258 lines (212 loc) · 7.59 KB
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
'use strict';
/**
* Action: FunctionRun
* - Runs the function in the CWD for local testing
*/
module.exports = function(S) {
const path = require('path'),
SError = require(S.getServerlessPath('Error')),
SCli = require(S.getServerlessPath('utils/cli')),
SUtils = S.utils,
BbPromise = require('bluebird'),
chalk = require('chalk');
/**
* FunctionRun Class
*/
class FunctionRun extends S.classes.Plugin {
static getName() {
return 'serverless.core.' + this.name;
}
registerActions() {
S.addAction(this.functionRun.bind(this), {
handler: 'functionRun',
description: `Runs the service locally. Reads the service’s runtime and passes it off to a runtime-specific runner`,
context: 'function',
contextAction: 'run',
options: [
{
option: 'region',
shortcut: 'r',
description: 'region you want to run your function in'
},
{
option: 'stage',
shortcut: 's',
description: 'stage you want to run your function in'
},
{
option: 'runDeployed',
shortcut: 'd',
description: 'invoke deployed function'
},
{
option: 'invocationType',
shortcut: 'i',
description: 'Valid Values: Event | RequestResponse | DryRun . Default is RequestResponse'
},
{
option: 'log',
shortcut: 'l',
description: 'Show the log output'
}
],
parameters: [
{
parameter: 'name',
description: 'The name of the function you want to run',
position: '0'
}
]
});
return BbPromise.resolve();
}
/**
* Action
*/
functionRun(evt) {
this.evt = evt;
// Flow
return this._prompt()
.bind(this)
.then(this._validateAndPrepare)
.then(() => {
// Run local or deployed
if (this.evt.options.runDeployed) {
return this._runDeployed();
} else {
return this._runLocal();
}
})
.then(() => this.evt);
}
_prompt() {
if (!S.config.interactive || this.evt.options.stage) return BbPromise.resolve();
return this.cliPromptSelectStage('Function Run - Choose a stage: ', this.evt.options.stage, false)
.then(stage => this.evt.options.stage = stage)
.then(() => this.cliPromptSelectRegion('Select a region: ', false, true, this.evt.options.region, this.evt.options.stage) )
.then(region => this.evt.options.region = region);
}
/**
* Validate And Prepare
*/
_validateAndPrepare() {
// If CLI and path is not specified, deploy from CWD if Function
if (S.cli && !this.evt.options.name) {
// Get all functions in CWD
if (!SUtils.fileExistsSync(path.join(process.cwd(), 's-function.json'))) {
return BbPromise.reject(new SError('You must be in a function folder to run it'));
}
this.evt.options.name = SUtils.readFileSync(path.join(process.cwd(), 's-function.json')).name
}
this.function = S.getProject().getFunction(this.evt.options.name);
// Missing function
if (!this.function) return BbPromise.reject(new SError(`Function ${this.evt.options.name} does not exist in your project.`));
// load event data if not it not present already
if (this.evt.data.event) return BbPromise.resolve();
return this._getEventFromStdIn()
.then(event => event || S.utils.readFile(this.function.getRootPath('event.json')))
.then(event => this.evt.data.event = event);
}
/**
* Get event data from STDIN
* If
*/
_getEventFromStdIn() {
return new BbPromise((resolve, reject) => {
const stdin = process.stdin;
const chunks = [];
const onReadable = () => {
const chunk = stdin.read();
if (chunk !== null) chunks.push(chunk);
};
const onEnd = () => {
try {
resolve(JSON.parse(chunks.join('')));
} catch(e) {
reject(new SError("Invalid event JSON"));
}
};
stdin.setEncoding('utf8');
stdin.on('readable', onReadable);
stdin.on('end', onEnd);
setTimeout((() => {
stdin.removeListener('readable', onReadable);
stdin.removeListener('end', onEnd);
stdin.end()
resolve()
}), 5);
});
}
/**
* Run Local
*/
_runLocal() {
const name = this.evt.options.name;
const stage = this.evt.options.stage;
const region = this.evt.options.region;
const event = this.evt.data.event;
if (!name) return BbPromise.reject(new SError('Please provide a function name to run'));
SCli.log(`Running ${name}...`);
return this.function.run(stage, region, event)
.then(result => this.evt.data.result = result);
}
/**
* Run Deployed
*/
_runDeployed() {
const stage = this.evt.options.stage;
this.evt.options.invocationType = this.evt.options.invocationType || 'RequestResponse';
this.evt.options.region = this.evt.options.region || S.getProject().getAllRegions(stage)[0].name;
const region = this.evt.options.region;
if (this.evt.options.invocationType !== 'RequestResponse') {
this.evt.options.logType = 'None';
} else {
this.evt.options.logType = this.evt.options.log ? 'Tail' : 'None'
}
// validate stage: make sure stage exists
if (!S.getProject().validateStageExists(stage)) {
return BbPromise.reject(new SError(`Stage "${stage}" does not exist in your project`, SError.errorCodes.UNKNOWN));
}
// validate region: make sure region exists in stage
if (!S.getProject().validateRegionExists(stage, region)) {
return BbPromise.reject(new SError(`Region "${region}" does not exist in stage "${stage}"`));
}
// Invoke Lambda
let params = {
FunctionName: this.function.getDeployedName({ stage, region }),
// ClientContext: new Buffer(JSON.stringify({x: 1, y: [3,4]})).toString('base64'),
InvocationType: this.evt.options.invocationType,
LogType: this.evt.options.logType,
Payload: new Buffer(JSON.stringify(this.evt.data.event)),
Qualifier: stage
};
return S.getProvider('aws')
.request('Lambda', 'invoke', params, stage, region)
.then( reply => {
const color = !reply.FunctionError ? 'white' : 'red';
if (reply.Payload) {
const response = JSON.parse(reply.Payload);
if (S.config.interactive) console.log(chalk[color](JSON.stringify(response, null, 4)));
this.evt.data.result = {
response,
status: reply.FunctionError ? 'error' : 'success'
};
}
if (reply.LogResult) {
console.log(chalk.gray('--------------------------------------------------------------------'));
const logResult = new Buffer(reply.LogResult, 'base64').toString();
logResult.split('\n').forEach( line => console.log(SCli.formatLambdaLogEvent(line)) );
}
})
.catch(e => {
this.evt.data.result = {
status: 'error',
message: e.message,
stack: e.stack
};
return BbPromise.reject(e);
});
}
}
return( FunctionRun );
};