-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
302 lines (257 loc) · 13.7 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
let archiver = require('archiver');
let aws = require('aws-sdk');
let exec = require('child_process').exec;
let fs = require('fs-extra');
let path = require('path');
let os = require('os');
const shortUuid = require('short-uuid');
let Server = require('./lib/server');
let ApiGatewayManager = require('./lib/ApiGatewayManager');
let LambdaManager = require('./lib/LambdaManager');
let ApiConfiguration = require('./lib/ApiConfiguration');
let BucketManager = require('./lib/BucketManager');
let CloudFormationDeployer = require('./lib/CloudFormationDeployer');
let LockFinder = require('./lib/lockFinder');
function AwsArchitect(packageMetadata, apiOptions, contentOptions) {
this.PackageMetadata = packageMetadata || {};
this.ContentOptions = contentOptions || {};
this.deploymentBucket = (apiOptions || {}).deploymentBucket;
this.SourceDirectory = (apiOptions || {}).sourceDirectory;
if (!aws.config.region && apiOptions.regions && apiOptions.regions[0]) {
aws.config.update({ region: apiOptions.regions[0] });
}
this.Configuration = new ApiConfiguration(apiOptions, 'index.js', aws.config.region || 'us-east-1');
if (this.Configuration.Regions.length === 0) { throw new Error('A single region must be defined in the apiOptions.'); }
if (this.Configuration.Regions.length > 1) { throw new Error('Only deployments to a single region are allowed at this time.'); }
this.Region = this.Configuration.Regions[0];
this.ApiGatewayManager = new ApiGatewayManager(this.PackageMetadata.name, this.PackageMetadata.version, this.Region);
this.LambdaManager = new LambdaManager(this.Region);
let s3Factory = new aws.S3({ region: this.Region });
this.BucketManager = new BucketManager(s3Factory, this.ContentOptions.bucket);
this.CloudFormationDeployer = new CloudFormationDeployer(this.Region, this.BucketManager, this.deploymentBucket);
}
async function GetAccountIdPromise() {
const callerData = await new aws.STS().getCallerIdentity().promise();
return callerData.Account;
}
AwsArchitect.prototype.publishZipArchive = async function(options = {}) {
if (!options.zipFileName || !this.deploymentBucket || !options.sourceDirectory) {
throw Error('The zipFileName, sourceDirectory, api options deploymentBucket must be specified.');
}
let tmpDir = path.join(os.tmpdir(), `zipDirectory-${shortUuid.generate()}`);
await new Promise((resolve, reject) => { fs.stat(options.sourceDirectory, (error, stats) => error || !stats.isDirectory ? reject(error || 'NotDirectoryError') : resolve()); });
await fs.copy(options.sourceDirectory, tmpDir);
let zipArchivePath = path.join(tmpDir, options.zipFileName);
await new Promise((resolve, reject) => {
let zipStream = fs.createWriteStream(zipArchivePath);
zipStream.on('close', () => resolve());
let archive = archiver.create('zip', {});
archive.on('error', e => reject({ Error: e }));
archive.pipe(zipStream);
archive.glob('**', { dot: true, cwd: tmpDir, ignore: options.zipFileName });
archive.finalize();
});
await this.BucketManager.DeployLambdaPromise(this.deploymentBucket, zipArchivePath, `${this.PackageMetadata.name}/${this.PackageMetadata.version}/${options.zipFileName}`);
};
AwsArchitect.prototype.publishLambdaArtifactPromise = AwsArchitect.prototype.PublishLambdaArtifactPromise = async function(options = {}) {
let lambdaZip = options && options.zipFileName || 'lambda.zip';
let tmpDir = path.join(os.tmpdir(), `lambda-${shortUuid.generate()}`);
await new Promise((resolve, reject) => {
fs.stat(this.SourceDirectory, (error, stats) => {
if (error) { return reject({ Error: `Path does not exist: ${this.SourceDirectory} - ${error}` }); }
if (!stats.isDirectory) { return reject({ Error: `Path is not a directory: ${this.SourceDirectory}` }); }
return resolve(null);
});
});
await fs.copy(this.SourceDirectory, tmpDir);
// (default: true) If set to true, will attempt to copy and install packages related to deployment (i.e. package.json for node)
if (options.autoHandleCompileOfSourceDirectory !== false) {
const lockFile = await new LockFinder().findLockFile(this.SourceDirectory);
if (lockFile.file) {
await fs.copy(lockFile.file, path.join(tmpDir, path.basename(lockFile.file)));
}
try {
await fs.writeJson(path.join(tmpDir, 'package.json'), this.PackageMetadata);
} catch (error) {
throw { Error: 'Failed writing production package.json file.', Details: error };
}
let cmd = lockFile.command;
await new Promise((resolve, reject) => {
/* eslint-disable-next-line no-unused-vars */
exec(cmd, { cwd: tmpDir }, (error, stdout, stderr) => {
if (error) { return reject({ Error: 'Failed installing production npm modules.', Details: error }); }
return resolve(tmpDir);
});
});
}
let zipArchivePath = path.join(tmpDir, lambdaZip);
await new Promise((resolve, reject) => {
let zipStream = fs.createWriteStream(zipArchivePath);
zipStream.on('close', () => resolve({ Archive: zipArchivePath }));
let archive = archiver.create('zip', {});
archive.on('error', e => reject({ Error: e }));
archive.pipe(zipStream);
archive.glob('**', { dot: true, cwd: tmpDir, ignore: lambdaZip });
archive.finalize();
});
let bucket = options && options.bucket || this.deploymentBucket;
if (bucket) {
await this.BucketManager.DeployLambdaPromise(bucket, zipArchivePath, `${this.PackageMetadata.name}/${this.PackageMetadata.version}/${lambdaZip}`);
}
};
AwsArchitect.prototype.validateTemplate = AwsArchitect.prototype.ValidateTemplate = function(stackTemplate, stackConfiguration) {
return this.CloudFormationDeployer.validateTemplate(stackTemplate, stackConfiguration && stackConfiguration.stackName, `${this.PackageMetadata.name}/${this.PackageMetadata.version}`);
};
AwsArchitect.prototype.deployTemplate = AwsArchitect.prototype.DeployTemplate = function(stackTemplate, stackConfiguration, parameters) {
return this.CloudFormationDeployer.deployTemplate(stackTemplate, stackConfiguration, parameters, `${this.PackageMetadata.name}/${this.PackageMetadata.version}`);
};
AwsArchitect.prototype.deployStackSetTemplate = async function(stackTemplate, stackConfiguration, parameters) {
try {
await new aws.IAM().getRole({ RoleName: 'AWSCloudFormationStackSetExecutionRole' }).promise();
} catch (error) {
if (error.code === 'NoSuchEntity') {
throw { title: 'Role "AWSCloudFormationStackSetExecutionRole" must exist. See prerequisite for cloudformation: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-prereqs-self-managed.html' };
}
throw error;
}
try {
await new aws.IAM().getRole({ RoleName: 'AWSCloudFormationStackSetAdministrationRole' }).promise();
} catch (error) {
if (error.code === 'NoSuchEntity') {
throw { title: 'Role "AWSCloudFormationStackSetAdministrationRole" must exist. See prerequisite for cloudformation: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-prereqs-self-managed.html' };
}
throw error;
}
let accountId = await GetAccountIdPromise();
return this.CloudFormationDeployer.deployStackSetTemplate(accountId, stackTemplate, stackConfiguration, parameters, `${this.PackageMetadata.name}/${this.PackageMetadata.version}`);
};
AwsArchitect.prototype.configureStackSetForAwsOrganization = async function(stackTemplate, stackConfiguration, parameters) {
try {
await new aws.IAM().getRole({ RoleName: 'AWSCloudFormationStackSetExecutionRole' }).promise();
} catch (error) {
if (error.code === 'NoSuchEntity') {
throw { title: 'Role "AWSCloudFormationStackSetExecutionRole" must exist. See prerequisite for cloudformation: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-prereqs-self-managed.html' };
}
throw error;
}
try {
await new aws.IAM().getRole({ RoleName: 'AWSCloudFormationStackSetAdministrationRole' }).promise();
} catch (error) {
if (error.code === 'NoSuchEntity') {
throw { title: 'Role "AWSCloudFormationStackSetAdministrationRole" must exist. See prerequisite for cloudformation: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-prereqs-self-managed.html' };
}
throw error;
}
return this.CloudFormationDeployer.configureStackSetForAwsOrganization(stackTemplate, stackConfiguration, parameters);
};
AwsArchitect.prototype.deployStagePromise = AwsArchitect.prototype.DeployStagePromise = function(stage, lambdaVersion) {
if (!stage) { throw new Error('Deployment stage is not defined.'); }
if (!lambdaVersion) { throw new Error('Deployment lambdaVersion is not defined.'); }
return this.ApiGatewayManager.GetApiGatewayPromise()
.then(restApi => this.ApiGatewayManager.DeployStagePromise(restApi, stage, lambdaVersion));
};
function getStageName(stage) {
return stage.replace(/[^a-zA-Z0-9-]/g, '-');
}
AwsArchitect.prototype.removeStagePromise = AwsArchitect.prototype.RemoveStagePromise = async function(stage, functionName) {
if (!stage) { throw new Error('Deployment stage is not defined.'); }
let stageName = getStageName(stage);
const apiGateway = await this.ApiGatewayManager.GetApiGatewayPromise();
const result = await this.ApiGatewayManager.RemoveStagePromise(apiGateway, stageName);
if (functionName) {
await this.LambdaManager.removeVersion(functionName, stageName);
}
return { title: 'Successfully deleted stage', stage: stageName, details: result };
};
AwsArchitect.prototype.deployLambdaFunctionVersion = async function(options = {}) {
let stage = options.stage;
let stageName = getStageName(stage);
let functionName = options.functionName;
let bucket = options.deploymentBucketName || this.deploymentBucket;
let deploymentKey = options.deploymentKeyName;
if (!stage) { throw new Error('Deployment stage is not defined.'); }
try {
const lambda = await this.LambdaManager.PublishNewVersion(functionName, bucket, deploymentKey);
const lambdaArn = lambda.FunctionArn;
const lambdaVersion = lambda.Version;
await this.LambdaManager.SetAlias(functionName, stageName, lambdaVersion);
return {
LambdaResult: {
LambdaFunctionArn: lambdaArn,
LambdaVersion: lambdaVersion
}
};
} catch (failure) {
throw { Error: 'Failed to create and deploy updates.', Details: failure };
}
};
AwsArchitect.prototype.publishAndDeployStagePromise = AwsArchitect.prototype.PublishAndDeployStagePromise = async function(options = {}) {
let stage = options.stage;
let stageName = getStageName(stage);
let functionName = options.functionName;
let bucket = options.deploymentBucketName || this.deploymentBucket;
let deploymentKey = options.deploymentKeyName;
if (!stage) { throw new Error('Deployment stage is not defined.'); }
try {
const lambda = await this.LambdaManager.PublishNewVersion(functionName, bucket, deploymentKey);
const lambdaArn = lambda.FunctionArn;
const lambdaVersion = lambda.Version;
await this.LambdaManager.SetAlias(functionName, stageName, lambdaVersion);
let apiGateway;
try {
apiGateway = await this.ApiGatewayManager.GetApiGatewayPromise();
} catch (error) {
if (error.code === 'ApiGatewayServiceNotFound') {
return {
LambdaResult: {
LambdaFunctionArn: lambdaArn,
LambdaVersion: lambdaVersion
}
};
}
throw error;
}
let accountId = await GetAccountIdPromise();
await this.LambdaManager.SetPermissionsPromise(accountId, lambdaArn, apiGateway.Id, this.Region, stageName);
const data = await this.ApiGatewayManager.DeployStagePromise(apiGateway, stageName, stage, lambdaVersion);
return {
LambdaResult: {
LambdaFunctionArn: lambdaArn,
LambdaVersion: lambdaVersion
},
ApiGatewayResult: data,
ServiceApi: `https://${apiGateway.Id}.execute-api.${this.Region}.amazonaws.com/${stageName}`
};
} catch (failure) {
throw { Error: 'Failed to create and deploy updates.', Details: failure };
}
};
AwsArchitect.prototype.cleanupPreviousFunctionVersions = async function(functionName, forceRemovalOfAliases) {
await this.LambdaManager.cleanupProduction(functionName, forceRemovalOfAliases, false);
};
AwsArchitect.prototype.publishWebsite = AwsArchitect.prototype.PublishWebsite = function(version, options = {}) {
if (!this.BucketManager.Bucket) { throw new Error('Bucket in content options has not been defined.'); }
if (!this.ContentOptions.contentDirectory) { throw new Error('Content directory is not defined.'); }
return this.BucketManager.Deploy(this.ContentOptions.contentDirectory, version, options.cacheControlRegexMap || [], options.contentTypeMappingOverride);
};
AwsArchitect.prototype.deleteWebsiteVersion = function(version) {
if (!this.BucketManager.Bucket) { throw new Error('Bucket in content options has not been defined.'); }
if (!version) { throw new Error('Website version is required.'); }
return this.BucketManager.deletePath(version);
};
AwsArchitect.prototype.run = AwsArchitect.prototype.Run = async function(port, logger) {
try {
let indexPath = path.join(this.SourceDirectory, 'index.js');
let api = require(indexPath);
let server = new Server(this.ContentOptions.contentDirectory, api, logger);
let attemptPort = port || 8080;
let resolvedPort = await server.Run(attemptPort);
if (resolvedPort !== attemptPort) {
console.log('Requested Port is in use. Using the next available port.');
}
return Promise.resolve({ title: `Server started successfully at 'http://localhost:${resolvedPort}', lambda routes available at /api, /triggers/event, /triggers/schedule.`, server });
} catch (exception) {
return Promise.reject({ title: 'Failed to start server', error: exception.stack || exception });
}
};
module.exports = AwsArchitect;