forked from MadSkills-io/fullstack-serverless
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
631 lines (536 loc) · 25.2 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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
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');
const invalidateCloudfrontDistribution = require('./lib/cloudFront');
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.getCLIOptions('confirm') === false || this.options.noConfirm === true) ? 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));
});
}
setClientEnv() {
this.serverless.cli.log(`Setting the environment variables...`);
const serverlessEnv = this.serverless.service.provider.environment;
if (!serverlessEnv) {
return this.serverless.cli.log(
`No environment variables detected. Skipping step...`
);
}
return Object.assign({}, process.env, serverlessEnv);
}
generateClient() {
const clientCommand = this.options.clientCommand;
const clientSrcPath = this.options.clientSrcPath || '.';
if (clientCommand && this.getCLIOptions('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 clientEnv = this.setClientEnv();
const proc = spawn(command, args, {cwd: clientSrcPath, env: clientEnv, 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() {
if(this.getCLIOptions('client-deploy') !== false) {
let region,
distributionFolder,
clientPath,
bucketName,
headerSpec,
indexDoc,
errorDoc,
invalidationPaths;
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";
invalidationPaths = this.options.invalidationPaths || ['/*'];
if (!Array.isArray(invalidationPaths)) {
invalidationPaths = [invalidationPaths];
}
//paths must start with '/'
invalidationPaths = invalidationPaths.map(path => path[0] === '/' ? path : '/' + path);
const deployDescribe = ['This deployment will:'];
if (this.getCLIOptions('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.getCLIOptions('confirm') === false || this.options.noConfirm === true) ? 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.getCLIOptions('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.`
);
});
}
this.serverless.cli.log('Client deployment cancelled');
return BbPromise.resolve();
})
.then(() => {
if (this.getCLIOptions('invalidate-distribution') === false) {
this.serverless.cli.log(`Skipping cloudfront invalidation...`);
} else {
return invalidateCloudfrontDistribution(this.serverless, invalidationPaths);
}
})
.catch(error => {
return BbPromise.reject(new this.error(error));
});
} else {
this.serverless.cli.log(`Skipping client deployment...`);
}
}
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.setApiGatewayIdFromConfig(baseResources)) {
this.removeApiGatewayOrigin(baseResources);
}
return baseResources;
}
removeApiGatewayOrigin(baseResources) {
this.serverless.cli.log(`ApiGatewayRestApi not found, removing origin 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';
}));
}
setApiGatewayIdFromConfig(baseResources) {
const restApiId = this.getRestApiId();
if (!restApiId) {
return false;
}
const distributionConfig = baseResources.Resources.ApiDistribution.Properties.DistributionConfig;
const apiOrigin = distributionConfig.Origins.find(origin => origin.Id === 'ApiGateway');
apiOrigin.DomainName = {
'Fn::Join': ['', [restApiId, '.execute-api.', {
Ref: 'AWS::Region'
}, '.amazonaws.com']]
};
return true;
}
getRestApiId() {
const apiGatewaySection = this.serverless.service.provider.apiGateway;
if (apiGatewaySection && apiGatewaySection.restApiId) {
return apiGatewaySection.restApiId;
}
return this.getConfig('apiGatewayRestApiId', null);
}
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);
this.prepareMinimumProtocolVersion(distributionConfig);
this.prepareDefaultCacheBehavior(distributionConfig);
this.prepareAliases(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) {
var localDomain;
try {
localDomain = domain.split(',');
} catch (e) {
localDomain = domain;
}
this.serverless.cli.log(`Adding domain alias ${localDomain}...`);
distributionConfig.Aliases = Array.isArray(localDomain) ? localDomain : [localDomain];
} else {
delete distributionConfig.Aliases;
}
}
prepareAliases(resources) {
const route53Id = this.getConfig('route53Id', null);
const route53Domain = this.getConfig('route53Domain', null);
for (let i = 0; i < resources.ApiDistribution.Properties.DistributionConfig.Aliases.length; i++) {
var alias = resources.ApiDistribution.Properties.DistributionConfig.Aliases[i];
// Alias is in the hosted zone domain, so we can add this record.
if (alias.endsWith('.'+route53Domain)) {
var name = i==0 ? "" : i;
resources["PublicDNS"+name] = {
"Type" : "AWS::Route53::RecordSet",
"Properties" : {
"HostedZoneId" : route53Id,
"Name" : alias,
"ResourceRecords" : [ {'Fn::GetAtt': ["ApiDistribution", "DomainName"]} ],
"TTL" : "900",
"Type" : "CNAME"
}
}
}
}
}
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()}'...`);
for (var origin of distributionConfig.Origins) {
if (origin.Id === 'ApiGateway') {
origin.OriginPath = `/${this.getStage()}`;
}
}
const customOrigins = this.getConfig('origins', null);
if (customOrigins) {
distributionConfig.Origins.push(
...customOrigins
);
}
}
preparePathPattern(distributionConfig) {
const customCacheBehaviors = this.getConfig('cacheBehaviors', null);
if (customCacheBehaviors) {
for (let customCacheBehavior of customCacheBehaviors) {
for (let cacheBehavior of distributionConfig.CacheBehaviors) {
if (cacheBehavior.TargetOriginId === customCacheBehavior.TargetOriginId) {
let index = distributionConfig.CacheBehaviors.indexOf(cacheBehavior);
distributionConfig.CacheBehaviors.splice(index, 1);
}
}
}
distributionConfig.CacheBehaviors.push(
...customCacheBehaviors
);
}
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;
}
}
prepareMinimumProtocolVersion(distributionConfig) {
const minimumProtocolVersion = this.getConfig('minimumProtocolVersion', undefined);
if (minimumProtocolVersion) {
distributionConfig.ViewerCertificate.MinimumProtocolVersion = minimumProtocolVersion;
}
}
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 distribution 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;
}
prepareDefaultCacheBehavior(distributionConfig) {
const defaultCacheBehavior = this.getConfig('defaultCacheBehavior', {})
const compressWebContent = this.getConfig('compressWebContent', true);
distributionConfig.DefaultCacheBehavior = Object.assign({},
distributionConfig.DefaultCacheBehavior,
defaultCacheBehavior,
{ Compress: compressWebContent }
);
}
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;
}
/**
* Serverless v3 hotfix/compat.
* @param {the cli option} param
* @returns Boolean
*/
getCLIOptions(param) {
// v3
const isv3 = this.serverless.version.split('.')[0] === '3';
if (isv3) {
const cliOptionsParams = Array.isArray(this.cliOptions?.param) ? [...this.cliOptions.param] : [];
const cliOptions = {...this.cliOptions}
// Build key/value cli options from param array
cliOptionsParams.forEach((k) => {
const key = k.replace('no-', '');
const val = !k.includes('no');
cliOptions[key] = val;
});
return cliOptions[param]
}
// v2
return this.cliOptions[param]
}
}
module.exports = ServerlessFullstackPlugin;