forked from MadSkills-io/fullstack-serverless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
538 lines (468 loc) · 22.1 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
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
const path = require('path');
const _ = require('lodash');
const chalk = require('chalk');
const yaml = require('js-yaml');
const fs = require('fs');
const {spawn} = require('child_process');
const BbPromise = require('bluebird');
const Confirm = require('prompt-confirm');
const bucketUtils = require('./lib/bucketUtils');
const uploadDirectory = require('./lib/upload');
const validateClient = require('./lib/validate');
class ServerlessFullstackPlugin {
constructor(serverless, cliOptions) {
this.error = serverless.classes.Error;
this.serverless = serverless;
this.options = serverless.service.custom.fullstack;
this.cliOptions = cliOptions || {};
this.aws = this.serverless.getProvider('aws');
this.hooks = {
'package:createDeploymentArtifacts': this.createDeploymentArtifacts.bind(this),
'aws:info:displayStackOutputs': this.printSummary.bind(this),
'client:client': () => this.serverless.cli.log(this.commands.client.usage),
'before:client:deploy:deploy': this.generateClient.bind(this),
'client:deploy:deploy': this.processDeployment.bind(this),
'client:remove:remove': this.removeDeployedResources.bind(this),
'after:aws:deploy:deploy:updateStack': () => this.serverless.pluginManager.run(['client', 'deploy']),
'before:remove:remove': () => this.serverless.pluginManager.run(['client', 'remove']),
'before:aws:package:finalize:mergeCustomProviderResources': this.checkForApiGataway.bind(this)
};
this.commands = {
client: {
usage: 'Generate and deploy clients',
lifecycleEvents: ['client', 'deploy'],
commands: {
deploy: {
usage: 'Deploy serverless client code',
lifecycleEvents: ['deploy']
},
remove: {
usage: 'Removes deployed files and bucket',
lifecycleEvents: ['remove']
}
}
}
};
}
validateConfig() {
try {
validateClient(this.serverless, this.options);
} catch (e) {
return BbPromise.reject(`Fullstack serverless configuration errors:\n- ${e.join('\n- ')}`);
}
return BbPromise.resolve();
}
removeDeployedResources() {
let bucketName;
return this.validateConfig()
.then(() => {
bucketName = this.getBucketName(this.options.bucketName);
return this.cliOptions.confirm === false ? true : new Confirm(`Are you sure you want to delete bucket '${bucketName}'?`).run();
})
.then(goOn => {
if (goOn) {
this.serverless.cli.log(`Looking for bucket '${bucketName}'...`);
return bucketUtils.bucketExists(this.aws, bucketName).then(exists => {
if (exists) {
this.serverless.cli.log(`Deleting all objects from bucket...`);
return bucketUtils
.emptyBucket(this.aws, bucketName)
.then(() => {
this.serverless.cli.log(
`Success! Your client files have been removed`
);
});
} else {
this.serverless.cli.log(`Bucket does not exist`);
}
});
}
this.serverless.cli.log('Bucket not removed');
return BbPromise.resolve();
})
.catch(error => {
return BbPromise.reject(new this.error(error));
});
}
generateClient() {
const clientCommand = this.options.clientCommand;
const clientSrcPath = this.options.clientSrcPath || '.';
if (clientCommand && this.cliOptions['generate-client'] !== false) {
const args = clientCommand.split(' ');
const command = args.shift();
return new BbPromise(this.performClientGeneration.bind(this, command, args, clientSrcPath));
} else {
this.serverless.cli.log(`Skipping client generation...`);
}
return BbPromise.resolve();
}
performClientGeneration(command, args, clientSrcPath, resolve, reject) {
this.serverless.cli.log(`Generating client...`);
const proc = spawn(command, args, {cwd: clientSrcPath, env: process.env, shell: true});
proc.stdout.on('data', (data) => {
const printableData = data ? `${data}`.trim() : '';
this.serverless.cli.consoleLog(` ${chalk.dim(printableData)}`);
});
proc.stderr.on('data', (data) => {
const printableData = data ? `${data}`.trim() : '';
this.serverless.cli.consoleLog(` ${chalk.red(printableData)}`);
});
proc.on('close', (code) => {
if (code === 0) {
this.serverless.cli.log(`Client generation process succeeded...`);
resolve();
} else {
reject(new this.error(`Client generation failed with code ${code}`));
}
});
}
processDeployment() {
let region,
distributionFolder,
clientPath,
bucketName,
headerSpec,
indexDoc,
errorDoc;
return this.validateConfig()
.then(() => {
// region is set based on the following order of precedence:
// If specified, the CLI option is used
// If region is not specified via the CLI, we use the region option specified
// under custom/client in serverless.yml
// Otherwise, use the Serverless region specified under provider in serverless.yml
region =
this.cliOptions.region ||
this.options.region ||
_.get(this.serverless, 'service.provider.region');
distributionFolder = this.options.distributionFolder || path.join('client/dist');
clientPath = path.join(this.serverless.config.servicePath, distributionFolder);
bucketName = this.getBucketName(this.options.bucketName);
headerSpec = this.options.objectHeaders;
indexDoc = this.options.indexDocument || "index.html";
errorDoc = this.options.errorDocument || "error.html";
const deployDescribe = ['This deployment will:'];
if (this.cliOptions['delete-contents'] !== false) {
deployDescribe.push(`- Remove all existing files from bucket '${bucketName}'`);
}
deployDescribe.push(
`- Upload all files from '${distributionFolder}' to bucket '${bucketName}'`
);
deployDescribe.forEach(m => this.serverless.cli.log(m));
return this.cliOptions.confirm === false ? true : new Confirm(`Do you want to proceed?`).run();
})
.then(goOn => {
if (goOn) {
this.serverless.cli.log(`Looking for bucket '${bucketName}'...`);
return bucketUtils
.bucketExists(this.aws, bucketName)
.then(exists => {
if (exists) {
this.serverless.cli.log(`Bucket found...`);
if (this.cliOptions['delete-contents'] === false) {
this.serverless.cli.log(`Keeping current bucket contents...`);
return BbPromise.resolve();
}
this.serverless.cli.log(`Deleting all objects from bucket...`);
return bucketUtils.emptyBucket(this.aws, bucketName);
} else {
this.serverless.cli.log(`Bucket does not exist. Run ${chalk.black('serverless deploy')}`);
return BbPromise.reject('Bucket does not exist!');
}
})
.then(() => {
this.serverless.cli.log(`Uploading client files to bucket...`);
return uploadDirectory(this.aws, bucketName, clientPath, headerSpec);
})
.then(() => {
this.serverless.cli.log(
`Success! Client deployed.`
);
})
.then(() => {
return this.invalidateClientStack();
});
}
this.serverless.cli.log('Client deployment cancelled');
return BbPromise.resolve();
})
.catch(error => {
return BbPromise.reject(new this.error(error));
});
}
invalidateClientStack() {
let apiDistributionId,
invalidationId;
if (this.cliOptions['invalidate-distribution'] === false) {
this.serverless.cli.log(`Skipping cloudfront invalidation...`);
} else {
return this.aws.request('CloudFormation', 'listStackResources', {StackName: this.aws.naming.getStackName()}).then(stacks => {
const apiDistribution = _.find(stacks.StackResourceSummaries, (stack) => {
return stack.LogicalResourceId === 'ApiDistribution'
});
if(!apiDistribution) {
this.serverless.cli.log(`Skipping cloudfront invalidation because cloudformation resource was not found`);
return;
}
apiDistributionId = apiDistribution.PhysicalResourceId;
})
.then(() => {
var params = {
DistributionId: apiDistributionId,
InvalidationBatch: {
CallerReference: Date.now().toString(),
Paths: {
Quantity: 1,
Items: ['/*']
}
}
};
return this.aws.request('CloudFront', 'createInvalidation', params)
.then(resp => {
this.serverless.cli.log(`CloudFront Invalidation started...`);
invalidationId = resp.Invalidation.Id;
})
})
.then(() => {
const isDistributionInvalidated = () => {
var params = {
DistributionId: apiDistributionId,
Id: invalidationId
};
return new Promise((resolve, reject) => this.aws.request('CloudFront', 'getInvalidation', params).then(status => {
if(status.Invalidation.Status === 'Completed') {
return resolve(true)
} else {
return resolve(false)
}
}));
}
const waitForInvalidationToComplete = () => {
return new Promise((resolve, reject) => {
const distributionPoll = setInterval(() => {
isDistributionInvalidated().then(result => {
if(result) {
clearInterval(distributionPoll);
return resolve();
}
})
}, 1000)
})
}
return waitForInvalidationToComplete()
})
.then(() => {
this.serverless.cli.log('Success! CloudFront invalidation completed.');
return BbPromise.resolve();
});
}
}
createDeploymentArtifacts() {
const baseResources = this.serverless.service.provider.compiledCloudFormationTemplate;
const filename = path.resolve(__dirname, 'lib/resources/resources.yml');
const content = fs.readFileSync(filename, 'utf-8');
const resources = yaml.safeLoad(content, {
filename: filename
});
this.prepareResources(resources);
return _.merge(baseResources, resources);
}
checkForApiGataway() {
const baseResources = this.serverless.service.provider.compiledCloudFormationTemplate;
const apiGatewayConfig = baseResources.Resources.ApiGatewayRestApi;
if (!apiGatewayConfig) {
this.serverless.cli.log(`ApiGatewayRestApi not found, removing orgin from CloudFront...`);
const distributionConfig = baseResources.Resources.ApiDistribution.Properties.DistributionConfig;
distributionConfig.Origins = _.filter(distributionConfig.Origins, (origin => {
return origin.Id !== 'ApiGateway';
}));
distributionConfig.CacheBehaviors = _.filter(distributionConfig.CacheBehaviors, (cacheBehavior => {
return cacheBehavior.TargetOriginId !== 'ApiGateway';
}));
}
return baseResources;
}
printSummary() {
const awsInfo = _.find(this.serverless.pluginManager.getPlugins(), (plugin) => {
return plugin.constructor.name === 'AwsInfo';
});
if (!awsInfo || !awsInfo.gatheredData) {
return;
}
const outputs = awsInfo.gatheredData.outputs;
const apiDistributionDomain = _.find(outputs, (output) => {
return output.OutputKey === 'ApiDistribution';
});
if (!apiDistributionDomain || !apiDistributionDomain.OutputValue) {
return;
}
const cnameDomain = this.getConfig('domain', '-');
this.serverless.cli.consoleLog(chalk.yellow('CloudFront domain name'));
this.serverless.cli.consoleLog(` ${apiDistributionDomain.OutputValue} (CNAME: ${cnameDomain})`);
}
prepareResources(resources) {
const distributionConfig = resources.Resources.ApiDistribution.Properties.DistributionConfig;
this.prepareLogging(distributionConfig);
this.prepareDomain(distributionConfig);
this.preparePriceClass(distributionConfig);
this.prepareOrigins(distributionConfig);
this.preparePathPattern(distributionConfig);
this.prepareComment(distributionConfig);
this.prepareCertificate(distributionConfig);
this.prepareWaf(distributionConfig);
this.prepareSinglePageApp(resources.Resources);
this.prepareS3(resources.Resources);
}
prepareLogging(distributionConfig) {
const loggingBucket = this.getConfig('logging.bucket', null);
if (loggingBucket !== null) {
this.serverless.cli.log(`Setting up logging bucket...`);
distributionConfig.Logging.Bucket = loggingBucket;
distributionConfig.Logging.Prefix = this.getConfig('logging.prefix', '');
} else {
this.serverless.cli.log(`Removing logging bucket...`);
delete distributionConfig.Logging;
}
}
prepareDomain(distributionConfig) {
const domain = this.getConfig('domain', null);
if (domain !== null) {
this.serverless.cli.log(`Adding domain alias ${domain}...`);
distributionConfig.Aliases = Array.isArray(domain) ? domain : [domain];
} else {
delete distributionConfig.Aliases;
}
}
preparePriceClass(distributionConfig) {
const priceClass = this.getConfig('priceClass', 'PriceClass_All');
this.serverless.cli.log(`Setting price class ${priceClass}...`);
distributionConfig.PriceClass = priceClass;
}
prepareOrigins(distributionConfig) {
this.serverless.cli.log(`Setting ApiGateway stage to '${this.getStage()}'...`);
const originPath = this.getConfig('originPath', null);
for (var origin of distributionConfig.Origins) {
if (origin.Id === 'ApiGateway') {
origin.OriginPath = `/${this.getStage()}`;
} else if (origin.Id === 'WebApp' && originPath !== null) {
origin.OriginPath = originPath;
}
}
}
preparePathPattern(distributionConfig) {
const apiPath = this.getConfig('apiPath', 'api');
this.serverless.cli.log(`Setting API path prefix to '${apiPath}'...`);
for (let cacheBehavior of distributionConfig.CacheBehaviors) {
if (cacheBehavior.TargetOriginId === 'ApiGateway') {
cacheBehavior.PathPattern = `${apiPath}/*`;
}
}
}
prepareComment(distributionConfig) {
const name = this.serverless.getProvider('aws').naming.getApiGatewayName();
distributionConfig.Comment = `Serverless Managed ${name}`;
}
prepareCertificate(distributionConfig) {
const certificate = this.getConfig('certificate', null);
if (certificate !== null) {
this.serverless.cli.log(`Configuring SSL certificate...`);
distributionConfig.ViewerCertificate.AcmCertificateArn = certificate;
} else {
delete distributionConfig.ViewerCertificate;
}
}
prepareWaf(distributionConfig) {
const waf = this.getConfig('waf', null);
if (waf !== null) {
this.serverless.cli.log(`Enabling web application firewall...`);
distributionConfig.WebACLId = waf;
} else {
delete distributionConfig.WebACLId;
}
}
prepareSinglePageApp(resources) {
const distributionConfig = resources.ApiDistribution.Properties.DistributionConfig;
const isSinglePageApp = this.getConfig('singlePageApp', false);
if (isSinglePageApp) {
this.serverless.cli.log(`Configuring distrobution for single page web app...`);
const indexDocument = this.getConfig('indexDocument', 'index.html')
for (let errorResponse of distributionConfig.CustomErrorResponses) {
if (errorResponse.ErrorCode === '403') {
errorResponse.ResponsePagePath = `/${indexDocument}`;
}
}
// Cloudfront default root object
distributionConfig.DefaultRootObject = indexDocument;
// Remove public read access to bucket, as all access is through the API for single page apps
const statements = resources.WebAppS3BucketPolicy.Properties.PolicyDocument.Statement;
resources.WebAppS3BucketPolicy.Properties.PolicyDocument.Statement = _.filter(statements, (statement) => {
return statement.Sid !== 'AllowPublicRead';
});
for (let origin of distributionConfig.Origins) {
if (origin.Id === 'WebApp') {
delete origin.CustomOriginConfig;
}
}
} else {
delete distributionConfig.CustomErrorResponses;
delete resources.S3OriginAccessIdentity;
// Remove API access to S3 bucket since all content will be served through http
const statements = resources.WebAppS3BucketPolicy.Properties.PolicyDocument.Statement;
resources.WebAppS3BucketPolicy.Properties.PolicyDocument.Statement = _.filter(statements, (statement) => {
return statement.Sid !== 'OAIGetObject';
});
for (let origin of distributionConfig.Origins) {
if (origin.Id === 'WebApp') {
delete origin.S3OriginConfig;
origin.DomainName = {
// Select hostname
"Fn::Select": ["1",
{
// Split URL into protocol and hostname
"Fn::Split": ["://",
{
// Get the bucket URL
'Fn::GetAtt': ["WebAppS3Bucket", "WebsiteURL"]
}
]
}
]
}
}
}
}
}
prepareS3(resources) {
const bucketName = this.getConfig('bucketName', null);
if (bucketName !== null) {
const stageBucketName = this.getBucketName(bucketName);
this.serverless.cli.log(`Setting up '${stageBucketName}' bucket...`);
resources.WebAppS3Bucket.Properties.BucketName = stageBucketName;
resources.WebAppS3BucketPolicy.Properties.Bucket = stageBucketName;
} else {
this.serverless.cli.log(`Setting up '${resources.WebAppS3Bucket.Properties.BucketName}' bucket...`);
}
const indexDocument = this.getConfig('indexDocument', 'index.html');
const errorDocument = this.getConfig('errorDocument', 'error.html');
this.serverless.cli.log(`Setting indexDocument to '${indexDocument}'...`);
this.serverless.cli.log(`Setting errorDocument to '${errorDocument}'...`);
resources.WebAppS3Bucket.Properties.WebsiteConfiguration.IndexDocument = indexDocument;
resources.WebAppS3Bucket.Properties.WebsiteConfiguration.ErrorDocument = errorDocument;
}
getBucketName(bucketName) {
const stageBucketName = `${this.serverless.service.service}-${this.getStage()}-${bucketName}`;
return stageBucketName;
}
getConfig(field, defaultValue) {
return _.get(this.serverless, `service.custom.fullstack.${field}`, defaultValue)
}
getStage() {
// find the correct stage name
var stage = this.serverless.service.provider.stage;
if (this.cliOptions && this.cliOptions.stage) {
stage = this.cliOptions.stage;
}
return stage;
}
}
module.exports = ServerlessFullstackPlugin;