Repository navigation
Expand file tree
/
Copy pathsshutil.js
More file actions
101 lines (88 loc) · 3.27 KB
/
Copy pathsshutil.js
File metadata and controls
101 lines (88 loc) · 3.27 KB
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
const Client = require('ssh2').Client;
const fs = require('fs');
const logger = require('./log');
const SLEEP = Symbol("sleep");
const RESET = Symbol("reset");
const HIBERNATE = Symbol("hibernate");
const SHUTDOWN = Symbol("shutdown");
class SSHUtil {
constructor() { //TODO: config on constructor + observable
}
get SLEEP() { return SLEEP; }
get RESET() { return RESET; }
get HIBERNATE() { return HIBERNATE; }
get SHUTDOWN() { return SHUTDOWN; }
op(operation, machines, config) {
switch (operation) {
case SLEEP:
return this.sleep(machines, config);
case SHUTDOWN:
return this.shutdown(machines, config);
case RESET:
return this.reset(machines, config);
case HIBERNATE:
return this.hibernate(machines, config);
default:
return Promise.reject(`Unknown operation ${operation}`);
}
}
sleep(machines, config) {
return this.executeAll('sudo pm-suspend', machines, config);
}
shutdown(machines, config) {
return this.executeAll('sudo poweroff', machines, config);
}
hibernate(machines, config) {
return this.executeAll('sudo pm-hibernate', machines, config);
}
reset(machines, config) {
return this.executeAll('sudo reboot', machines, config);
}
executeAll(command, machines, config) {
let arr = ( machines instanceof Array ) ? machines : ( ( machines ) ? [machines] : [] );
if ( arr.length == 0 ) return Promise.resolve("");
return arr.map( (m) => { return this.execute(command, m, config);});
}
execute(command, machine, config) {
//console.log(config);
var conn = new Client();
return new Promise( (resolve, reject) => {
conn.on('ready', function() {
logger.info('Client :: ready');
conn.exec(command, (err, stream) =>{
if (err) {
logger.error(err);
reject(err);
} else {
var msg = "";
stream.on('close', (code, signal) => {
logger.info('Stream :: close :: code: ' + code + ', signal: ' + signal);
if ( code == undefined || code == null || code == 0 ) {
resolve("")
} else {
reject(`Sleep status code=[${code}]`)
}
conn.end();
}).on('data', (data) => {
logger.info(data);
}).stderr.on('data', (data) => {
msg = data;
logger.error(data);
});
}
});
}).on('error', (err)=> {
console.log(err);
reject(err);
}).connect({
host: machine.ipaddress,
port: machine.sshPort,
username: config.userName,
privateKey: fs.readFileSync(config.sshKeyPath)
});
})
}
}
module.exports = () => {
return new SSHUtil();
};