-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
301 lines (257 loc) · 10 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
/* eslint-env node */
'use strict';
const BasePlugin = require('ember-cli-deploy-plugin');
const RSVP = require('rsvp');
const fs = require('fs-extra');
const path = require('path');
const archiver = require('archiver');
const AWS = require('aws-sdk');
const DEFAULT_DEPLOY_INFO = 'fastboot-deploy-info.json';
const DEFAULT_DEPLOY_ARCHIVE = 'dist';
module.exports = {
name: 'ember-cli-deploy-fastboot-s3',
createDeployPlugin(options) {
const name = options.name;
const DeployPlugin = BasePlugin.extend({
name,
defaultConfig: {
archivePath: path.join('tmp', DEFAULT_DEPLOY_ARCHIVE),
archiveType: 'zip',
deployInfo: DEFAULT_DEPLOY_INFO,
deployArchive: DEFAULT_DEPLOY_ARCHIVE,
distDir: (context) => context.distDir,
revisionKey: (context) => (
context.commandOptions.revision ||
(context.revisionData && context.revisionData.revisionKey)
),
s3Client: (context) => context.s3Client,
},
requiredConfig: ['bucket'],
configure(/*context*/) {
// Ensure default config is applied
this._super.configure.apply(this, arguments);
// If a custom S3 client is configured then the rest of the
// configuration is redundant.
if (this.readConfig('s3Client')) {
return;
}
// An endpoints makes the region config redundant, however
// at least one of them must be present.
if (!this.readConfig('region') && !this.readConfig('endpoint')) {
const message = `You must configure either an 'endpoint' or a 'region' to use the AWS.S3 client.`;
this.log(message, { color: 'red' });
throw new Error(message);
}
},
setup(/*context*/) {
this.s3 =
this.readConfig('s3Client') ||
new AWS.S3({
region: this.readConfig('region'),
accessKeyId: this.readConfig('accessKeyId'),
secretAccessKey: this.readConfig('secretAccessKey'),
endpoint: this.readConfig('endpoint')
});
},
didPrepare(/*context*/) {
return this._pack()
.then(() => {
const archiveName = this._buildArchiveName();
this.log(`✔ ${archiveName}`, { verbose: true });
});
},
upload(/*context*/) {
const prefix = this.readConfig('prefix');
const archiveName = this._buildArchiveName();
this.key = prefix ? [prefix, archiveName].join('/') : archiveName;
return this._upload(this.s3)
.then(() => {
this.log(`✔ ${this.key}`, { verbose: true });
return RSVP.Promise.resolve();
})
.catch(this._errorMessage.bind(this));
},
activate(context) {
const revisionKey = this.readConfig('revisionKey');
this.log(`preparing to activate ${revisionKey}`, {
verbose: true
});
let _this = this;
return this.fetchRevisions(context).then(function(revisions) {
let found = revisions.revisions.map(function(element) { return element.revision; }).indexOf(revisionKey);
if (found >= 0) {
return _this._uploadDeployInfo(_this.s3)
.then(() => {
if(!context.revisionData) {
context.revisionData = {};
}
context.revisionData.activatedRevisionKey = revisionKey;
_this.log(`✔ activated revison ${revisionKey}`, {
verbose: true
});
})
.catch(_this._errorMessage.bind(_this));
} else {
return RSVP.reject("REVISION NOT FOUND!"); // see how we should handle a pipeline failure
}
});
},
didDeploy(context) {
const revisionKey = context.revisionData && context.revisionData.revisionKey;
const activatedRevisionKey = context.revisionData && context.revisionData.activatedRevisionKey;
if (revisionKey && !activatedRevisionKey) {
this.log("Deployed but did not activate revision " + revisionKey + ". "
+ "To activate, run: "
+ "ember deploy:activate " + context.deployTarget + " --revision=" + revisionKey + "\n"
);
}
},
fetchRevisions(context) {
return this._list(context)
.then(function(revisions) {
return {
revisions: revisions
};
});
},
_list(/* context */) {
const bucket = this.readConfig('bucket');
const deployArchive = this.readConfig('deployArchive');
const archiveExt = `.${this.readConfig('archiveType')}`;
const deployInfo = this.readConfig('deployInfo');
const prefix = this.readConfig('prefix');
const archivePath = prefix ? [prefix, deployArchive].join('/') : deployArchive;
const indexKey = prefix ? [prefix, deployInfo].join('/') : deployInfo;
let revisionPrefix = `${archivePath}-`;
return RSVP.hash({
revisions: this.listObjects(this.s3, { Bucket: bucket, Prefix: revisionPrefix }),
current: this.getObject(this.s3, { Bucket: bucket, Key: indexKey }),
})
.then(function(data) {
let activeRevision = '';
if (data.current) {
let objectData = data.current.Body.toString('utf-8');
if (objectData[0] === '{') {
let obj = JSON.parse(objectData);
if (obj.key) {
activeRevision = obj.key.substring(revisionPrefix.length, obj.key.lastIndexOf('.'));
}
}
}
let results = data.revisions.Contents.sort(function(a, b) {
return new Date(b.LastModified) - new Date(a.LastModified);
}).map(function(d) {
let revision = '';
/* Check that this is the type of configured archive. */
if (d.Key.lastIndexOf(archiveExt) !== -1) {
revision = d.Key.substring(revisionPrefix.length, d.Key.lastIndexOf('.'));
}
let active = data.current && revision === activeRevision;
return { revision: revision, timestamp: d.LastModified, active: active, deployer: 'fastboot-s3' };
}).filter(function(d) {
/* Filter out results where revision is empty. */
return d.revision !== '';
});
return results;
}).catch(this._errorMessage.bind(this));
},
listObjects(s3, params) {
return new RSVP.Promise(function(resolve, reject) {
s3.listObjects(params, function(err, data) {
if (err) {
return reject(err);
}
return resolve(data);
});
});
},
getObject(s3, params) {
return new RSVP.Promise(function(resolve, reject) {
s3.getObject(params, function(err, data) {
if (err && (err.code === 'NotFound' || err.code === 'NoSuchKey')) {
return resolve();
}
else if (err) {
return reject(err);
}
else {
return resolve(data);
}
});
});
},
_upload(s3) {
const archivePath = this.readConfig('archivePath');
const archiveName = this._buildArchiveName();
const prefix = this.readConfig('prefix');
const key = prefix ? [prefix, archiveName].join('/') : archiveName;
const fileName = path.join(archivePath, archiveName);
const file = fs.createReadStream(fileName);
const bucket = this.readConfig('bucket');
const params = {
Bucket: bucket,
Key: key,
Body: file
};
this.log(`preparing to upload to S3 bucket '${bucket}'`, {
verbose: true
});
return s3.putObject(params).promise();
},
_uploadDeployInfo(s3 /*, key*/) {
const deployInfo = this.readConfig('deployInfo');
const bucket = this.readConfig('bucket');
const prefix = this.readConfig('prefix');
const body = this._createDeployInfo();
const key = prefix ? [prefix, deployInfo].join('/') : deployInfo;
const params = {
Bucket: bucket,
Key: key,
Body: body
};
return s3.putObject(params).promise();
},
_createDeployInfo() {
const bucket = this.readConfig('bucket');
const prefix = this.readConfig('prefix');
const archiveName = this._buildArchiveName();
const key = prefix ? [prefix, archiveName].join('/') : archiveName;
return `{"bucket":"${bucket}","key":"${key}"}`;
},
_pack() {
return new RSVP.Promise((resolve, reject) => {
const distDir = this.readConfig('distDir');
const archivePath = this.readConfig('archivePath');
const archiveType = this.readConfig('archiveType');
const deployArchive = this.readConfig('deployArchive');
fs.mkdirsSync(archivePath);
const archiveName = this._buildArchiveName();
const fileName = path.join(archivePath, archiveName);
this.log(`saving deploy archive to ${fileName}`, {
verbose: true
});
const output = fs.createWriteStream(fileName);
const archive = archiver(archiveType, { zlib: { level: 9 } });
archive.pipe(output);
archive.directory(distDir, deployArchive).finalize();
output.on('close', resolve);
archive.on('error', (err) => reject(err));
});
},
_buildArchiveName() {
const deployArchive = this.readConfig('deployArchive');
const revisionKey = this.readConfig('revisionKey');
const archiveType = this.readConfig('archiveType');
return `${deployArchive}-${revisionKey}.${archiveType}`;
},
_errorMessage(error) {
this.log(error, { color: 'red' });
if (error) {
this.log(error.stack, { color: 'red' });
}
return RSVP.Promise.reject(error);
}
});
return new DeployPlugin();
}
};