-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
299 lines (224 loc) · 9.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
var fs = require('fs-extra');
var path = require('path');
var EventEmitter = require('events').EventEmitter;
var assert = require('assert');
var format = require('chalk');
var async = require('async');
var tmp = require('tmp');
var ask = require('ask');
var asArray = require('as-array');
var dumper = require('divshot-dumper');
var statusHandler = require('./lib/status-handler');
var syncTree = require('./lib/sync-tree');
var filesToUpload = require('./lib/files-to-upload');
var DIVSHOT_API_VERSION = '0.5.0';
var DIVSHOT_API_HOST = 'https://api.divshot.com';
var DEFAULT_ENVIRONMENT = 'development';
var DEFAULT_AWS_REGION = 'us-east-1';
var DEFAULT_AWS_BUCKET = 'divshot-io-hashed-production';
var CACHE_DIRECTORY = '.divshot-cache/deploy';
module.exports = function push (options) {
// Set up status events stream
var status = statusHandler();
// Ensure required data
assert.ok(options.config, '[divshot-push]: Application configuration data is required');
assert.ok(options.token, '[divshot-push]: User authentication token is required');
// Set up options
var environment = options.environment || DEFAULT_ENVIRONMENT;
var config = options.config;
var token = options.token;
var timeout = options.timeout;
var awsBucket = (options.bucket) ? options.hosting.bucket || DEFAULT_AWS_BUCKET : DEFAULT_AWS_BUCKET;
var appConfigRootPath = (config.root && config.root === '/') ? './' : config.root || './';
var appRootDir = path.resolve(options.root || '/', appConfigRootPath);
var apiHost = (options.hosting) ? options.hosting.api.host || DIVSHOT_API_HOST : DIVSHOT_API_HOST;
var apiVersion = (options.hosting) ? options.hosting.api.version || DIVSHOT_API_VERSION : DIVSHOT_API_VERSION;
var cacheDirectory = options.cacheDirectory || CACHE_DIRECTORY;
// Set up api calls
var api = ask({
origin: apiHost,
headers: {
'Authorization': 'Bearer ' + token,
'Accept-Version': apiVersion
}
});
// Log output on error
dumper(api.events);
var createApp = api.post('apps');
// Use nextTick because we need to listen for events
// outside the module before we start emitting the events
process.nextTick(function () {
startDeploy(config);
});
function startDeploy (config) {
if (!fs.existsSync(appRootDir)) {
return status.emit('error', 'The directory ' + format.bold(appRootDir) + ' does not exist');
}
status.emit('build:start');
// Start deployment process
deploy(config);
}
function deploy (config) {
var createBuild = api.post('apps', config.name, 'builds');
createBuild({config: config})
.then(function (res) {
var build = res.body;
// Any other error
if (build.status || build.error) {
return status.emit('error', res.body.error);
}
// Unexptected error
if (!build.loadpoint) {
var errorMsg = '';
errorMsg += 'Unexpected build data.\n';
errorMsg += format.red.underline('====== Build Data Start ======\n');
errorMsg += JSON.stringify(build, null, 4) + '\n';
errorMsg += format.red.underline('====== Build Data End ======\n');
errorMsg += '\nContact support@divshot.com with this data for diagnostic purposes.';
return status.emit('error', errorMsg);
}
status.emit('build:end', build);
startUpload(config, build);
})
.catch(function (err) {
// App doesn't exist yet, create it first
if (err.statusCode === 404) {
return createAppBeforeBuild(config);
}
if (err.statusCode === 401) {
return status.emit('error', err.body.error);
}
status.emit('error', (err.body) ? err.body.error: err);
});
// 4. Copy files (minus exclusions) to a tmp dir
function startUpload (config, build) {
status.emit('hashing:start');
tmp.dir({unsafeCleanup: true}, function(err, tmpDir) {
async.map(filesToUpload(appRootDir, config.exclude), function(src, callback){
// This seems to be the main place path seperators are getting us into trouble.
var _appRootDir = appRootDir.replace(/\\/g, '/');
src = src.replace(/\\/g, '/');
if (fs.statSync(src).isDirectory()) { callback(); return; };
var dest = src.replace(_appRootDir, tmpDir + "/" + build.id).replace(/\\/g, '/');
fs.ensureFileSync(dest);
fs.copySync(src, dest);
callback() ;
}, function() {
// 5. get the STS token for the build formatted for our S3 lib
var authorization = JSON.parse(new Buffer(build.loadpoint.authorization, 'base64'));
// 6. upload files syncTree
var directory = [tmpDir, build.id].join('/');
var sync = syncTree({
clientOptions: {
secretAccessKey: authorization.secret,
accessKeyId: authorization.key,
sessionToken: authorization.token,
region: DEFAULT_AWS_REGION,
httpOptions: {
timeout: timeout
}
},
directory: [tmpDir, build.id].join('/'),
bucket: process.env.DIVSHOT_HASHED_BUCKET || awsBucket,
prefix: build.application_id,
cacheDirectory: cacheDirectory
});
sync.on('inodecount', function(count) {
status.emit('hashing:end');
status.emit('file:count', count);
status.emit('upload:start', count);
});
sync.on('notfound', function(path, hash) {
status.emit('notfound');
verbose(format.red('404 ') + path);
});
sync.on('found', function(path, hash, count) {
status.emit('file:found', count);
status.emit('upload:progress', count);
verbose(format.green('200 ') + path);
});
sync.on('cachestart', function(path, hash) {
status.emit('file:cachestart');
verbose(format.blue('PUT ') + path);
});
sync.on('cachesuccess', function(path, hash, count) {
status.emit('file:cachesuccess');
status.emit('upload:progress', 1);
verbose(format.green('201 ') + path);
});
sync.on('uploadsuccess', function(path, hash) {
status.emit('upload:success');
status.emit('upload:progress', 1);
status.emit('upload:end');
verbose(format.green('201 ') + path);
});
sync.on('uploadfailure', function(err) {
status.emit('upload:failure', err);
status.emit('upload:error', err);
});
sync.on('retry', function(err) {
status.emit('upload:retry', err);
});
sync.on('error', function(err) {
status.emit('error', err);
});
sync.on('synced', function(fileMap) {
status.emit('upload:start', Object.keys(fileMap).length);
status.emit('upload:end');
var finalizeBuild = api.put(
'apps',
config.name.toLowerCase(),
'builds',
build.id,
'finalize'
);
var releaseBuild = api.post(
'apps',
config.name.toLowerCase(),
'releases',
environment
);
status.emit('finalize:start');
finalizeBuild({file_map: fileMap})
.then(function (res) {
status.emit('finalize:end');
status.emit('release:start', environment);
return releaseBuild({build: build.id})
})
.then(function (res) {
status.emit('release:end');
// TODO: should not hard code this
var appUrl = (environment === 'production')
? 'http://' + config.name + '.divshot.io'
: 'http://' + environment + '.' + config.name + '.divshot.io';
status.emit('end', {
url: appUrl,
environment: environment
});
})
.catch(function (err) {
status.emit('error', (err.body) ? err.body.error: err);
});
});
});
});
}
}
function createAppBeforeBuild (config) {
status.emit('app:create', config.name);
createApp({name: config.name.toLowerCase()})
.then(function (res) {
status.emit('app:end', res.body);
deploy(config);
})
.catch(function (err) {
status.emit('error', (err.body) ? err.body.error: err);
});
}
// Handle verbose data for debugging
function verbose() {
status.emit('verbose', asArray(arguments));
}
// Return event emitter
return status;
};