-
Notifications
You must be signed in to change notification settings - Fork 10
/
Remote.js
354 lines (290 loc) · 10.3 KB
/
Remote.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
const {Client} = require('ssh2');
const fs = require('fs');
const exec = require('child_process').exec;
const async = require('async');
const path = require('path');
const shellEscape = require('any-shell-escape');
const utils = require('./utils');
const cliProgress = require('cli-progress');
const chalk = require('chalk');
const humanFormat = require('human-format');
/**
* Remote
* @type {{}}
*/
module.exports = class {
constructor(options, logger, onError) {
this.options = options;
this.logger = logger;
this.onError = onError;
if (options.privateKeyFile) {
options.privateKey = fs.readFileSync(options.privateKeyFile);
}
}
/**
* Initiate SSH and SCP connection
* @param onReady
* @param onError
* @param onClose
*/
connect(onReady, onError, onClose) {
// Instantiate connection
this.connection = new Client();
// Register events
this.connection.on('ready', onReady);
this.connection.on('error', onError);
this.connection.on('close', onClose);
if (this.options.onKeyboardInteractive) {
this.connection.on('keyboard-interactive', this.options.onKeyboardInteractive);
}
const connectionOptions = Object.assign({}, this.options);
// If debug is enabled, proxy output to console.log
if (connectionOptions.debug) {
connectionOptions.debug = console.log;
}
// Connect
this.connection.connect(connectionOptions);
}
/**
* Exec command on remote using SSH connection
* @param command
* @param {Function} done A NodeJS error first-callback. The second argument is a string representing the command output.
* @param log Log result
*/
exec(command, done, log) {
this.connection.exec(command, (error, stream) => {
const stdout = [];
const stderr = [];
if (error) {
this.onError(command, error);
}
stream.stderr.on('data', data => {
stderr.push(data.toString());
this.logger.error(`STDERR: ${data}`);
});
stream.on('data', data => {
stdout.push(data.toString());
if (log) {
this.logger.log(`STDOUT: ${data}`);
return;
}
this.logger.debug(`STDOUT: ${data}`);
});
stream.on('close', (exitCode, exitSignal) => {
// Error
if (exitCode !== 0) {
this.logger.fatal('This command returns an error : "' + command + '"');
}
this.logger.debug(`Remote command : ${command}`);
done(null, exitCode, exitSignal, stdout, stderr);
});
});
}
/**
* Exec multiple commands on remote using SSH connection
* @param commands
* @param done
* @param log Log result
*/
execMultiple(commands, done, log) {
async.eachSeries(commands, (command, itemCallback) => {
this.exec(command, (error, exitCode, exitSignal, stdout, stderr) => {
itemCallback();
}, log);
}, done);
}
/**
* Upload file on remote
* @param src
* @param target
* @param done
*/
upload(src, target, done) {
this.connection.sftp((err, sftp) => {
if (err) {
return done(err);
}
this.logger.debug(`Uploading file ${src} => ${target}`);
const progressBar = new cliProgress.SingleBar({
format: `|${chalk.cyan('{bar}')}| {bytesTransferred}/{bytesTotal} || {percentage}% || Elapsed: {duration_formatted}`,
hideCursor: true
}, cliProgress.Presets.shades_classic);
progressBar.start(100, 0, {
bytesTotal: null,
bytesTransferred: 0,
});
sftp.fastPut(
src,
target,
{
chunkSize: 500,
step: (bytesTransferred, chunkSize, bytesTotal) => {
progressBar.update(bytesTransferred / bytesTotal * 100, {
bytesTransferred: humanFormat(bytesTransferred, { scale: 'binary', unit: 'B' }),
bytesTotal: humanFormat(bytesTotal, { scale: 'binary', unit: 'B' }),
});
}
},
(err) => {
progressBar.stop();
done(err);
}
);
});
}
/**
* Synchronize local folder src to remote folder target
* @param src
* @param synchronizedFolder
* @param done
*/
synchronize(src, target, synchronizedFolder, done) {
const source = src + '/';
const fullTarget = this.options.username + '@' + this.options.host + ':' + synchronizedFolder;
const escapedUsername = shellEscape(this.options.username);
// Construct rsync command
let remoteShell = '';
// Use password
if (this.options.password != '') {
const escapedPassword = shellEscape(this.options.password);
remoteShell = `--rsh='sshpass -p "${escapedPassword}" ssh -l ${escapedUsername} -p ${this.options.port} -o StrictHostKeyChecking=no'`;
}
// Use privateKey
else if (this.options.privateKeyFile != null) {
const escapedPrivateKeyFile = shellEscape(this.options.privateKeyFile);
let passphrase = '';
if (this.options.passphrase) {
passphrase = `sshpass -p'${(shellEscape(this.options.passphrase))}' -P"assphrase for key"`;
}
remoteShell = `--rsh='${passphrase} ssh -l ${escapedUsername} -i ${escapedPrivateKeyFile} -p ${this.options.port} -o StrictHostKeyChecking=no'`;
}
// Excludes
const excludes = this.options.exclude.map(path => `--exclude=${shellEscape(path)}`);
// Compression
let compression = this.options.compression !== false ? '--compress': '';
if (typeof this.options.compression === 'number') {
compression += ` --compress-level=${this.options.compression}`;
}
// Concat
const synchronizeCommand = [
'rsync',
remoteShell,
...this.options.rsyncOptions,
compression,
...excludes,
'--delete-excluded',
'-a',
'--stats',
'--delete',
source,
fullTarget
].join(' ');
// Exec !
this.logger.debug(`Local command : ${synchronizeCommand}`);
exec(synchronizeCommand, (error, stdout, stderr) => {
if (error) {
this.logger.fatal(error);
return;
}
if (stdout) {
this.logger.log(stdout);
}
if (stderr) {
this.logger.log(stderr);
}
this.synchronizeRemote(
this.options.deployPath + '/' + this.options.synchronizedFolder,
target,
done
);
});
}
/**
* Synchronize two remote folders
* @param src
* @param target
* @param done
*/
synchronizeRemote(src, target, done) {
const copy = 'rsync -a ' + src + '/ ' + target;
this.exec(copy, () => {
done();
});
}
/**
* Create symbolic link on remote
* @param target
* @param link
* @param done
*/
createSymboliclink(target, link, done) {
link = utils.realpath(link);
const symlinkTarget = utils.realpath(link + '/../' + target);
const commands = [
`mkdir -p \`dirname ${link}\``, // Create the parent of the symlink
`if test ! -e ${symlinkTarget}; then mkdir -p ${symlinkTarget}; fi`, // Create the symlink target, if it doesn't exist
`ln -nfs ${target} ${link}`
];
this.execMultiple(commands, done);
}
/**
* Chmod path on remote
* @param path
* @param mode
* @param done
*/
chmod(path, mode, done) {
const command = 'chmod ' + mode + ' ' + path;
this.exec(command, function () {
done();
});
}
/**
* Create folder on remote
* @param path
* @param done
*/
createFolder(path, done) {
const commands = [
'mkdir -p ' + path,
'chmod ugo+w ' + path
];
this.execMultiple(commands, done);
}
/**
* Remove old folders on remote
* @param folder
* @param numberToKeep
* @param done
*/
removeOldFolders(folder, numberToKeep, done) {
const commands = [
"cd " + folder + " && rm -rf `ls -r " + folder + " | awk 'NR>" + numberToKeep + "'`"
];
this.execMultiple(commands, () => {
done();
});
}
close(done) {
this.connection.end();
done();
}
getPenultimateRelease(done) {
return new Promise((resolve, reject) => {
const releasesPath = path.posix.join(this.options.deployPath, this.options.releasesFolder);
const getPreviousReleaseDirectoryCommand = `ls -r -d ${releasesPath}/*/ | grep -v rollbacked | awk 'NR==2'`;
this.exec(getPreviousReleaseDirectoryCommand, (err, exitCode, exitSignal, stdout, stderr) => {
if (err) {
reject(err);
return;
}
const penultimateRelease = stdout[0];
if (!penultimateRelease) {
reject('No previous release to rollback to');
return;
}
resolve(penultimateRelease);
});
});
}
};