This repository has been archived by the owner on Apr 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcli.js
executable file
·284 lines (262 loc) · 8.32 KB
/
cli.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
#!/usr/bin/env node
'use strict';
let fs = require('fs');
let path = require('path');
let aws = require('aws-sdk');
let argv = require('minimist')(process.argv.slice(2));
let JSZip = require('jszip');
let FileUtils = require('./fileUtils');
let log = (str) => {
process.stdout.write(str);
};
/**
* Provides CLI commands
*/
class CLI {
/**
* checks the right conv
*/
constructor() {
// parse the configuration object from local config
let env = process.env.NODE_ENV;
if (!env)
env = 'development';
if (env !== 'local') {
this.config =
require(process.cwd() + '/local.cloudhopper.config.json')[env];
let configArr = this.config.lambdaArn.split(':');
if (configArr.length > 9) {
console.log('That lambdaArn is longer than usual.');
process.exit(1);
}
this.config.region = configArr[3];
this.config.lambdaName = configArr[6];
if(configArr.length === 8)
this.config.lambdaQualifier = configArr[7];
}
}
/**
* run as a local express application
*/
runLocal() {
process.env.NODE_ENV = 'local';
this.config =
require(process.cwd() + '/local.cloudhopper.config.json')['local'];
for (let i in this.config.stageVariables) {
if (this.config.stageVariables.hasOwnProperty(i)) {
process.env[i] = this.config.stageVariables[i];
}
}
let appHandler = require(path.join(process.cwd(), 'index.js'));
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
app.use(bodyParser.text({type: '*/*'}));
app.use(function(req, res) {
appHandler.handler(req, {}, function(err, data) {
res
.status(data.statusCode)
.set(data.headers)
.send(data.body);
});
});
app.listen(3000, function() {
console.log('Express app listening on port 3000!');
})
;
}
/**
* Run as a command locally
* @param {Array<string>} args The name of function to execute
*/
execLocal(args) {
global.isCommand = true;
process.env.NODE_ENV = process.env.NODE_ENV || 'production';
console.log('ENV SET TO: ', process.env.NODE_ENV);
require(process.cwd() + '/index.js').handler(args);
}
/**
* upload the deployment package
*/
deploy() {
let fu = new FileUtils();
fu.setIgnoreFile('.gitignore');
fu.setIgnoredModules(['aws-sdk']);
let afterZip = () => {
console.log(`begin zip upload from `);
let lambda= new aws.Lambda({
region: this.config.region,
});
let s3= new aws.S3({
region: this.config.region,
});
let fileStream = fs.createReadStream(this.config.tempFile);
fileStream.on('open', function(self) {
return function() {
console.log('uploading to s3');
s3.putObject({
Bucket: self.config.tempS3Bucket,
Key: `${self.config.lambdaName}.temp.zip`,
ACL: 'public-read',
Body: fileStream,
}).promise()
// 1. Set all the envs to the $LATEST code
.then((data) => {
console.log('uploaded to s3: ', data);
// updateFunctionConfiguration will always update the $LATEST
// version of your lambda function
let params = {
FunctionName: self.config.lambdaName,
Environment: {
Variables: self.config.stageVariables,
},
};
console.log('now set the envs to the $LATEST code');
return lambda.updateFunctionConfiguration(params).promise();
})
// 2. update code of the $LATEST version
.then((data) => {
console.log('updated function conf:');
let params = {
FunctionName: self.config.lambdaName,
// ZipFile: fs.readFileSync(self.config.tempFile),
S3Bucket: self.config.tempS3Bucket,
S3Key: `${self.config.lambdaName}.temp.zip`,
Publish: ( process.env.NODE_ENV === 'production' ),
};
return lambda.updateFunctionCode(params).promise();
})
// update alias pointer of production if required
.then((data) => {
console.log('moved from s3 to lambda');
if (process.env.NODE_ENV === 'production') {
console.log('updating alias ', data.Version);
return lambda.updateAlias({
FunctionName: self.config.lambdaName,
Name: 'production',
FunctionVersion: data.Version,
}).promise();
}
})
.then((data) => {
console.log(data);
})
.catch(console.log);
};
}(this));
};
fu.includeDependenciesFiles(process.cwd(), true)
.then((files) => {
console.log('obtained list of files ', files.length);
let zip = new JSZip();
for (let i = 0; i < files.length; i ++) {
zip.file(
files[i].replace(process.cwd(), ''),
fs.readFileSync(files[i])
);
}
console.log('done..');
zip
.generateNodeStream({
type: 'nodebuffer',
streamFiles: true,
compression: 'DEFLATE',
compressionOptions: {
level: 9,
},
})
.pipe(fs.createWriteStream(this.config.tempFile))
.on('finish', () => {
console.log('zip file created');
afterZip();
});
});
}
/**
* Returns a swagger file
* @return {string} a json string for swagger file
*/
getSwag() {
let filename = `${__dirname}/sampleyaml/proxy.json`;
console.log('reading from filename: ', filename);
let swagJson = fs.readFileSync(filename, 'utf8');
swagJson = swagJson.replace(/LAMBDA_ARN/g, this.config.lambdaArn);
swagJson = swagJson.replace(/API_GATEWAY_TITLE/g, this.config.lambdaArn);
swagJson = swagJson.replace(/REGION/g, this.config.region);
console.log(swagJson);
return JSON.parse(swagJson);
}
/**
* Create a new API Gateway in the region
* 1. upload the swag file to API_G
* 2. create a new deployment to specified stage
* 3. check if lambda policy has permission for it
* 4. set up the policy permission on lambda
*/
setUpApi() {
log('API creating...\t\t');
let apigateway = new aws.APIGateway({
region: this.config.region,
});
apigateway.putRestApi({
restApiId: this.config.restApiId,
body: new Buffer(JSON.stringify(this.getSwag())),
mode: 'overwrite',
}).promise().then((data) => {
log('done\n');
return;
}).then(() => {
log('API deployment...\t\t');
return apigateway.createDeployment({
restApiId: this.config.restApiId,
stageName: this.config.stageName,
cacheClusterEnabled: false,
variables: this.config.stageVariables,
}).promise();
}).then((data) => {
log('done\n');
log(`URL: https://${this.config.restApiId}.execute-api.${this.config.region}.amazonaws.com/${this.config.stageName}\n`);
log('setting up permissions on lambda....');
// TODO: set up correct permissions on lambda function
let lambda= new aws.Lambda({
region: this.config.region,
});
let params = {
FunctionName: this.config.lambdaName,
};
if (this.config.lambdaQualifier) {
params.FunctionName =
this.config.lambdaName + ':' + this.config.lambdaQualifier;
}
return lambda.getPolicy(params).promise();
}).then((policy) => {
console.log(policy);
if (policy === null) {
console.log('but policy was null');
}
let existingPolicy = JSON.parse(policy.Policy);
console.log(existingPolicy);
// TODO
}).catch(console.log);
}
/**
* Print a help block
*/
help() {
let helpText = `
Usage:
npm run cloudhopper -- COMMAND
COMMAND can be one of:
1. setUpApi: overwrites the API Gateway to route all
data to lambda running cloudhopper
2. deploy: Creates a lambda deployment package and uploads it to lambda
3. runLocal: Prepares an express server and servers the API locally
4. help: displays this help text
`;
console.log(helpText);
}
}
let c = new CLI();
let f = c[argv._[0]];
f || c.help();
f && f.bind(c)(argv);