-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathloadBalance.js
51 lines (45 loc) · 1.47 KB
/
loadBalance.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
const { Client } = require('ssh2');
const fs = require('fs');
function executeCommand(server, command, callback) {
const conn = new Client();
conn.on('ready', () => {
conn.exec(command, (err, stream) => {
if (err) throw err;
let output = '';
stream.on('data', data => {
output += data.toString();
});
stream.on('close', () => {
conn.end();
callback(output.trim());
});
});
}).connect({
host: server.host,
username: server.creds.user,
privateKey: fs.readFileSync(server.creds.privateKey)
});
}
async function getCPUUsage(server) {
return new Promise((resolve, reject) => {
executeCommand(server, 'top -bn1 | grep "Cpu(s)"', cpuOutput => {
const cpuUsage = cpuOutput.match(/(\d+\.\d+)%? id/);
const cpuUsagePercentage = cpuUsage ? 100 - parseFloat(cpuUsage[1]) : Infinity;
resolve(cpuUsagePercentage);
});
});
}
async function findLeastLoadedServer(serverDataFilePath) {
const servers = require(serverDataFilePath);
let leastLoadedServer = null;
let minCPU = Infinity;
for (const server of servers) {
const cpuUsage = await getCPUUsage(server);
if (cpuUsage < minCPU) {
minCPU = cpuUsage;
leastLoadedServer = server;
}
}
return leastLoadedServer;
}
module.exports = findLeastLoadedServer;