forked from mikermcneil/sails-deploy-azure
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
341 lines (302 loc) · 12.9 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
/**
* Module dependences
*/
var path = require('path');
var _ = require('lodash');
var util = require('util');
var child_process = require('child_process');
var fs = require('fs');
var Azure = require('machinepack-azure');
var Spinner = require('node-spinner');
var log = require('single-line-log').stdout;
var prompt = require('prompt');
var colors = require('colors');
module.exports = function sailsDeployAzure(inputs, cb) {
// Get the package.json so we can display current Azur edeploy version
var addonPackageJson = require(path.resolve(__dirname, 'package.json')),
appPackageJson = require(path.resolve(process.cwd(), 'package.json'))
// Display welcome message
console.log('Microsoft Azure'.blue,'deploy v'+addonPackageJson.version+' starting...');
try {
// `inputs.config` is provided with the raw config that Sails core gathered by running `rc`.
//
// If `config` is missing or invalid, bail out w/ an error
// (we just throw an error w/ a helpful message, since the catch() below will take care of it)
if (!_.isObject(inputs.config)) {
return cb(new Error('Incomplete `config` provided to sails-deploy-azure! Expected `config` to exist and be an object.'));
}
var ifa = (inputs.config.azure) ? inputs.config.azure : null,
sitenameCli = (ifa && ifa.sitename) ? ifa.sitename : appPackageJson.name,
usernameCli = (ifa && ifa.username) ? ifa.username : null,
passwordCli = (ifa && ifa.password) ? ifa.password : null;
if (sitenameCli && usernameCli && passwordCli) {
// All three parameters given, assume that website already exists
deployToSite(sitenameCli, usernameCli, passwordCli, cb);
} else if (sitenameCli) {
// Only sitename given, check if it exists
createSite(sitenameCli, function(err, result) {
if (err) {return cb(err);}
deployToSite(sitenameCli, usernameCli, passwordCli, cb);
});
} else {
// Something went wrong
return cb(new Error('Deployment failed for unknown reason.'));
}
function createSite(sitename, callback) {
Azure.checkActiveSubscription().exec({
error: function (err){
return cb(new Error(require('util').format('Error checking for active subscription: %s', err)));
},
success: function (isActive){
(function (next){
if (isActive) {
return next();
}
Azure.registerAzureAccount({}, {
error: function (err) {next(err);},
success: function (result) {
next();
}
});
})(function afterwards(err){
if (err) {
return cb(new Error(require('util').format('Error registering Azure account: %s', err)));
}
var createOptions = sitename ? {name: sitename} : {};
Azure.existsWebsite(createOptions).exec({
error: function (err) {
return cb(new Error(require('util').format('Error creating Website: %s', err)));
},
success: function (result) {
if (result) {
console.log('Website already exists in account, moving on...');
var credentialsLink = 'https://manage.windowsazure.com/#Workspaces/WebsiteExtension/Website/' + sitename + '/dashboard';
credentialsLink = credentialsLink.underline.green;
console.log('You need to use deployment credentials. For security reasons, this step is manual.\n If not known, open ' + credentialsLink + ' and click "Set Deployment Credentials".'.red);
prompt.start();
prompt.get({
properties: {
username: {
description: "What is the deployment username?"
},
password: {
hidden: true,
description: "What is the deployment password?"
}
}
}, function (err, userInput) {
if (err) {
return cb(new Error(require('util').format('Error prompting for deployment credentials: %s', err)));
}
usernameCli = userInput.username;
passwordCli = userInput.password;
return callback();
});
} else {
console.log('Website does not exist in account, trying to create...');
Azure.createWebsite(createOptions).exec({
error: function (err) {
return callback(require('util').format('Error creating Website: %s', err));
},
success: function () {
var credentialsLink = 'https://manage.windowsazure.com/#Workspaces/WebsiteExtension/Website/' + sitename + '/dashboard';
credentialsLink = credentialsLink.underline.green;
console.log('Website ' + sitename + ' created.');
console.log('You need to use deployment credentials. For security reasons, this step is manual.\n If not known, open ' + credentialsLink + ' and click "Set Deployment Credentials".'.red);
prompt.start();
prompt.get({
properties: {
username: {
description: "What is the deployment username?"
},
password: {
hidden: true,
description: "What is the deployment password?"
}
}
}, function (err, userInput) {
if (err) {
return cb(new Error(require('util').format('Error prompting for deployment credentials: %s', err)));
}
usernameCli = userInput.username;
passwordCli = userInput.password;
return callback();
});
}
});
}
}
});
});
}
});
}
function deployToSite(sitename, username, password, callback) {
sitename = sitename || sitenameCli;
username = username || usernameCli;
password = password || passwordCli;
var jobOptions = {
deploymentUser: username,
deploymentPassword: password,
name: 'sailsdeploy.ps1',
website: sitename
};
console.log('Starting Deployment');
// (1) Create ZIP package -----------------------------------------------------------
zipSailsApp({}, {
error: function (err) {
return callback(new Error(require('util').format('Creating ZIP package failed: %s', err)));
},
success: function () {
console.log('ZIP package created.');
// (2) Upload File ------------------------------------------------------------------
Azure.uploadFile({
deploymentUser: username,
deploymentPassword: password,
fileLocation: getPathToDeploymentArchive(),
remotePath: 'site/temp/deployment.zip',
website: sitename
}).exec({
error: function (err) {
return callback(new Error(require('util').format('Uploading file failed: %s', err)));
},
success: function () {
console.log('Deployment package uploaded');
// (3) Upload Webjob ----------------------------------------------------------------
Azure.uploadWebjob({
deploymentUser: username,
deploymentPassword: password,
fileLocation: path.resolve(__dirname, './payload/sailsdeploy.ps1'),
website: sitename
}).exec({
error: function (err) {
return callback(new Error(require('util').format('Uploading webjob failed: %s', err)));
},
success: function (result) {
console.log('Deployment script uploaded');
// (4) Trigger Webjob ---------------------------------------------------------------
Azure.triggerWebjob(jobOptions).exec({
error: function (err) {
return callback(new Error(require('util').format('Triggering webjob failed: %s', err)));
},
success: function () {
console.log('Deployment script started');
// (5) Get Latest Webjob Log --------------------------------------------------------
var scriptDone = false;
var spinner = Spinner();
var retryCounter = 0;
var spinnerInterval = setInterval(function(){
process.stdout.write('\r \033[36mcomputing\033[m ' + spinner.next());
}, 250);
var getLog = function () {
Azure.logWebjob(jobOptions).exec({
error: function (err) {
// Retry 5 times before we fail
if (retryCounter <= 5) {
retryCounter = retryCounter + 1;
setTimeout(getLog, 800);
} else {
return callback(new Error('Failed to fetch script status'));
}
},
success: function (scriptOutput) {
if (scriptOutput.body && scriptOutput.body.indexOf('All done!') > -1) {
console.log('Deployment finished.')
console.log('The site should be available at ' + sitename + '.azurewebsites.net.');
clearInterval(spinnerInterval);
return cb();
} else {
if (scriptOutput.body) {
log(scriptOutput.body);
process.stdout.write('\r \033[36mcomputing\033[m ' + spinner.next());
}
setTimeout(getLog, 400);
}
}
});
};
getLog();
}
});
}
});
}
});
}
});
}
}
catch (e) {
console.error('Deployment to Azure failed! Details:\n',e.stack);
return cb(e);
}
};
/* Helper Methods */
/**
* ```
* getDeploymentArchiveStream().pipe(outs);
* ```
*
* @return {Readable} get the read stream pointing at the deployment.zip file.
*/
function getDeploymentArchiveStream() {
var fs = require('fs');
return fs.createReadStream(getPathToDeploymentArchive());
}
/**
* @return {String} the absolute path where the .zip deployment archive should live
*/
function getPathToDeploymentArchive(options) {
var path = require('path');
options = options || {
appPath: process.cwd()
};
// TODO: load app config and use configured tmp directory
var tmpDir = path.resolve(options.appPath, '.tmp/');
// TODO: configurable filename for archive, or use uuid
var archiveFilename = 'deployment.zip';
var archiveAbsPath = path.resolve(tmpDir, archiveFilename);
return archiveAbsPath;
}
/**
* WARNING: unfinished
* @param {[type]} inputs [description]
* @param {[type]} exits [description]
* @return {[type]} [description]
*/
function zipSailsApp(inputs, exits) {
var Zip = require('machinepack-zip');
var path = require('path');
var appPath = path.resolve(process.cwd(), inputs.dir || './');
// TODO ensure output folder exists
// TODO ensure src folders exist??
// Zip up the specified source files or directories and write a .zip file to disk.
Zip.zip({
// TODO: get all the things, not just the conventional things
sources: [
// Inject Azure Node Config
path.resolve(__dirname, './payload/iisnode.yml'),
path.resolve(__dirname, './payload/web.config'),
// Other Stuff
path.resolve(appPath, 'README.md'),
path.resolve(appPath, '.tmp'),
path.resolve(appPath, 'app.js'),
path.resolve(appPath, '.sailsrc'),
path.resolve(appPath, 'tasks'),
path.resolve(appPath, 'package.json'),
path.resolve(appPath, 'Gruntfile.js'),
path.resolve(appPath, 'assets'),
path.resolve(appPath, 'views'),
path.resolve(appPath, 'config'),
path.resolve(appPath, 'api')
],
destination: getPathToDeploymentArchive(),
}).exec({
// An unexpected error occurred.
error: exits.error,
// OK.
success: function () {
return exits.success();
}
});
}