significant code clean-up
Cleaned up the code in app.js. Started moving code into /functions.
This commit is contained in:
parent
46fb7e0faf
commit
dc5a456269
4 changed files with 207 additions and 146 deletions
192
app.js
192
app.js
|
@ -1,16 +1,12 @@
|
|||
const express = require("express");
|
||||
const session = require("express-session");
|
||||
const redis = require('connect-redis');
|
||||
const { currentLoad, mem, networkStats, fsSize, dockerContainerStats } = require('systeminformation');
|
||||
const app = express();
|
||||
const routes = require("./routes");
|
||||
const PORT = 8000;
|
||||
var Docker = require('dockerode');
|
||||
var docker = new Docker({ socketPath: '/var/run/docker.sock' });
|
||||
const { dashCard } = require('./components/dashCard');
|
||||
|
||||
let DockerContainers, sent_list, clicked, open_ports, ServerMetrics, card_list, external_port, internal_port;
|
||||
let container_stats = {};
|
||||
const { serverStats, containerList, containerStats, containerAction } = require('./functions/systeminformation');
|
||||
|
||||
let sent_list, clicked;
|
||||
|
||||
const redisClient = require('redis').createClient({
|
||||
legacyMode:true
|
||||
|
@ -39,174 +35,88 @@ app.use([
|
|||
routes
|
||||
]);
|
||||
|
||||
const server = app.listen(PORT, async () => {
|
||||
console.log(`App listening on port ${PORT}`);
|
||||
const server = app.listen(8000, async () => {
|
||||
console.log(`App listening on port 8000`);
|
||||
});
|
||||
|
||||
const io = require('socket.io')(server);
|
||||
io.engine.use(sessionMiddleware);
|
||||
|
||||
|
||||
|
||||
|
||||
io.on('connection', (socket) => {
|
||||
|
||||
// set user session
|
||||
const user_session = socket.request.session;
|
||||
console.log(`${user_session.user} connected from ${socket.handshake.headers.host} ${socket.handshake.address}`);
|
||||
|
||||
// display client connection info
|
||||
console.log(`${user_session.user} connected from ${socket.handshake.headers.host} ${socket.handshake.address} \n Active Sessions: ${io.engine.clientsCount}`);
|
||||
|
||||
// send list of running docker containers if sent_list contains data
|
||||
// check if a list of containers needs to be sent
|
||||
if (sent_list != null) { socket.emit('cards', sent_list); }
|
||||
|
||||
// check if an install is in progress
|
||||
// check if an install card has to be sent
|
||||
if((app.locals.install != '') && (app.locals.install != null)){
|
||||
socket.emit('install', app.locals.install);
|
||||
}
|
||||
|
||||
// send server metrics to client
|
||||
async function Metrics() {
|
||||
Promise.all([currentLoad(), mem(), networkStats(), fsSize()]).then(([cpuUsage, ramUsage, netUsage, diskUsage]) => {
|
||||
let cpu = Math.round(cpuUsage.currentLoad);
|
||||
let ram = Math.round(((ramUsage.active / ramUsage.total) * 100));
|
||||
let tx = netUsage[0].tx_bytes;
|
||||
let rx = netUsage[0].rx_bytes;
|
||||
let disk = diskUsage[0].use;
|
||||
socket.emit('metrics', { cpu, ram, tx, rx, disk });
|
||||
});
|
||||
}
|
||||
// send server metrics
|
||||
let ServerStats = setInterval(async () => {
|
||||
|
||||
async function ContainersList() {
|
||||
card_list = '';
|
||||
open_ports = '';
|
||||
external_port;
|
||||
internal_port;
|
||||
socket.emit('metrics', await serverStats());
|
||||
|
||||
docker.listContainers({ all: true }, async function (err, data) {
|
||||
|
||||
for (const container of data) {
|
||||
|
||||
console.log(container);
|
||||
}, 1000);
|
||||
|
||||
let imageVersion = container.Image.split('/');
|
||||
let service = imageVersion[imageVersion.length - 1].split(":")[0];
|
||||
// send container metrics
|
||||
let ContainerList = setInterval(async () => {
|
||||
|
||||
|
||||
let containerId = docker.getContainer(container.Id);
|
||||
let containerInfo = await containerId.inspect();
|
||||
let card_list = await containerList();
|
||||
|
||||
// console.log(containerInfo.Name.split('/')[1]);
|
||||
// console.log(container.Image);
|
||||
// console.log(containerInfo.HostConfig.RestartPolicy.Name);
|
||||
if (sent_list !== card_list) {
|
||||
sent_list = card_list;
|
||||
app.locals.install = '';
|
||||
socket.emit('cards', card_list);
|
||||
}
|
||||
}, 1000);
|
||||
|
||||
|
||||
for (const [key, value] of Object.entries(containerInfo.HostConfig.PortBindings)) {
|
||||
console.log(`${value[0].HostPort}:${key}`);
|
||||
external_port = value[0].HostPort;
|
||||
internal_port = key;
|
||||
|
||||
if (( external_port == undefined) || (internal_port == undefined)) {
|
||||
external_port = 0;
|
||||
internal_port = 0;
|
||||
}
|
||||
}
|
||||
|
||||
// let volumes = [];
|
||||
|
||||
// console.log('Volumes:');
|
||||
// for (const [key, value] of Object.entries(containerInfo.Mounts)) {
|
||||
// console.log(`${value.Source}: ${value.Destination}: ${value.RW}`);
|
||||
// volumes.push(`${value.Source}: ${value.Destination}: ${value.RW}`);
|
||||
// }
|
||||
|
||||
// console.log('Environment Variables:');
|
||||
// for (const [key, value] of Object.entries(containerInfo.Config.Env)) {
|
||||
// console.log(`${key}: ${value}`);
|
||||
// }
|
||||
|
||||
// console.log('Labels:');
|
||||
// for (const [key, value] of Object.entries(containerInfo.Config.Labels)) {
|
||||
// console.log(`${key}: ${value}`);
|
||||
// }
|
||||
|
||||
dockerContainerStats(container.Id).then((data) => {
|
||||
container_stats = {
|
||||
name: container.Names[0].slice(1),
|
||||
cpu: Math.round(data[0].cpuPercent),
|
||||
ram: Math.round(data[0].memPercent)
|
||||
}
|
||||
socket.emit('container_stats', container_stats);
|
||||
});
|
||||
|
||||
|
||||
|
||||
let container_info = {
|
||||
name: container.Names[0].slice(1),
|
||||
service: service,
|
||||
id: container.Id,
|
||||
state: container.State,
|
||||
image: container.Image,
|
||||
external_port: external_port,
|
||||
internal_port: internal_port
|
||||
}
|
||||
|
||||
let dockerCard = dashCard(container_info);
|
||||
// send container metrics
|
||||
let ContainerStats = setInterval(async () => {
|
||||
let container_stats = await containerStats();
|
||||
|
||||
|
||||
// open_ports += `-L ${external_port}:localhost:${external_port} `
|
||||
card_list += dockerCard;
|
||||
|
||||
}
|
||||
//split up the array to display the name and stats
|
||||
for (let i = 0; i < container_stats.length; i++) {
|
||||
socket.emit('container_stats', container_stats[i]);
|
||||
}
|
||||
|
||||
// emit card list is it's different from what was sent last time, then clear install local
|
||||
if (sent_list !== card_list) {
|
||||
sent_list = card_list;
|
||||
app.locals.install = '';
|
||||
socket.emit('cards', card_list);
|
||||
console.log('Cards updated');
|
||||
}
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
console.log('Starting Metrics');
|
||||
ServerMetrics = setInterval(Metrics, 1000);
|
||||
|
||||
console.log('Starting Containers List');
|
||||
DockerContainers = setInterval(ContainersList, 1000);
|
||||
}, 1000);
|
||||
|
||||
|
||||
socket.on('clicked', (data) => {
|
||||
// Prevent multiple clicks
|
||||
if (clicked == true) { return; } clicked = true;
|
||||
|
||||
console.log(`${socket.request.session.user} wants to: ${data.action} ${data.container}`);
|
||||
|
||||
if (socket.request.session.role == 'admin') {
|
||||
var containerName = docker.getContainer(data.container);
|
||||
|
||||
if ((data.action == 'start') && (data.state == 'stopped')) {
|
||||
containerName.start();
|
||||
} else if ((data.action == 'start') && (data.state == 'paused')) {
|
||||
containerName.unpause();
|
||||
} else if ((data.action == 'stop') && (data.state != 'stopped')) {
|
||||
containerName.stop();
|
||||
} else if ((data.action == 'pause') && (data.state == 'running')) {
|
||||
containerName.pause();
|
||||
} else if ((data.action == 'pause') && (data.state == 'paused')) {
|
||||
containerName.unpause();
|
||||
} else if (data.action == 'restart') {
|
||||
containerName.restart();
|
||||
}
|
||||
} else {
|
||||
console.log('User is not an admin');
|
||||
let buttonPress = {
|
||||
user: socket.request.session.user,
|
||||
role: socket.request.session.role,
|
||||
action: data.action,
|
||||
container: data.container,
|
||||
state: data.state
|
||||
}
|
||||
|
||||
console.log(buttonPress)
|
||||
|
||||
containerAction(buttonPress);
|
||||
|
||||
clicked = false;
|
||||
});
|
||||
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
console.log('Stopping Metrics');
|
||||
clearInterval(ServerMetrics);
|
||||
console.log('Stopping Containers List');
|
||||
clearInterval(DockerContainers);
|
||||
socket.on('disconnect', () => {
|
||||
clearInterval(ServerStats);
|
||||
clearInterval(ContainerList);
|
||||
clearInterval(ContainerStats);
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
});
|
|
@ -1,4 +1,4 @@
|
|||
function dashCard(data) {
|
||||
module.exports.dashCard = function dashCard(data) {
|
||||
|
||||
let { name, service, id, state, image, external_port, internal_port } = data;
|
||||
|
||||
|
@ -1064,6 +1064,4 @@ function dashCard(data) {
|
|||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
module.exports = { dashCard };
|
||||
}
|
150
functions/systeminformation.js
Normal file
150
functions/systeminformation.js
Normal file
|
@ -0,0 +1,150 @@
|
|||
const { currentLoad, mem, networkStats, fsSize, dockerContainerStats } = require('systeminformation');
|
||||
var Docker = require('dockerode');
|
||||
var docker = new Docker({ socketPath: '/var/run/docker.sock' });
|
||||
const { dashCard } = require('../components/dashCard');
|
||||
|
||||
|
||||
|
||||
module.exports.serverStats = async function () {
|
||||
const cpuUsage = await currentLoad();
|
||||
const ramUsage = await mem();
|
||||
const netUsage = await networkStats();
|
||||
const diskUsage = await fsSize();
|
||||
|
||||
const info = {
|
||||
cpu: Math.round(cpuUsage.currentLoad),
|
||||
ram: Math.round((ramUsage.active / ramUsage.total) * 100),
|
||||
tx: netUsage[0].tx_bytes,
|
||||
rx: netUsage[0].rx_bytes,
|
||||
disk: diskUsage[0].use,
|
||||
};
|
||||
|
||||
return info;
|
||||
}
|
||||
|
||||
|
||||
|
||||
module.exports.containerList = async function () {
|
||||
let card_list = '';
|
||||
|
||||
const data = await docker.listContainers({ all: true });
|
||||
for (const container of data) {
|
||||
let imageVersion = container.Image.split('/');
|
||||
let service = imageVersion[imageVersion.length - 1].split(':')[0];
|
||||
|
||||
let containerId = docker.getContainer(container.Id);
|
||||
let containerInfo = await containerId.inspect();
|
||||
|
||||
let open_ports = [];
|
||||
let external_port = 0;
|
||||
let internal_port = 0;
|
||||
|
||||
for (const [key, value] of Object.entries(containerInfo.HostConfig.PortBindings)) {
|
||||
open_ports.push(`${value[0].HostPort}`);
|
||||
external_port = value[0].HostPort;
|
||||
internal_port = key;
|
||||
|
||||
if ((external_port == undefined) || (internal_port == undefined)) {
|
||||
external_port = 0;
|
||||
internal_port = 0;
|
||||
}
|
||||
}
|
||||
|
||||
let volumes = [];
|
||||
for (const [key, value] of Object.entries(containerInfo.Mounts)) {
|
||||
volumes.push(`${value.Source}: ${value.Destination}: ${value.RW}`);
|
||||
}
|
||||
|
||||
let environment_variables = [];
|
||||
for (const [key, value] of Object.entries(containerInfo.Config.Env)) {
|
||||
environment_variables.push(`${key}: ${value}`);
|
||||
}
|
||||
|
||||
let labels = [];
|
||||
for (const [key, value] of Object.entries(containerInfo.Config.Labels)) {
|
||||
labels.push(`${key}: ${value}`);
|
||||
}
|
||||
|
||||
|
||||
let container_info = {
|
||||
name: container.Names[0].slice(1),
|
||||
service: service,
|
||||
id: container.Id,
|
||||
state: container.State,
|
||||
image: container.Image,
|
||||
external_port: external_port,
|
||||
internal_port: internal_port
|
||||
}
|
||||
|
||||
let dockerCard = dashCard(container_info);
|
||||
|
||||
card_list += dockerCard;
|
||||
|
||||
}
|
||||
|
||||
return card_list;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
module.exports.containerStats = async function () {
|
||||
|
||||
let container_stats = [];
|
||||
|
||||
const data = await docker.listContainers({ all: true });
|
||||
|
||||
for (const container of data) {
|
||||
|
||||
const stats = await dockerContainerStats(container.Id);
|
||||
let container_stat = {
|
||||
name: container.Names[0].slice(1),
|
||||
cpu: Math.round(stats[0].cpuPercent),
|
||||
ram: Math.round(stats[0].memPercent)
|
||||
}
|
||||
|
||||
//push stats to an array
|
||||
container_stats.push(container_stat);
|
||||
}
|
||||
return container_stats;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
module.exports.containerAction = async function (data) {
|
||||
|
||||
let { name, role, action, container, state } = data;
|
||||
|
||||
console.log(`${name} wants to: ${action} ${container}`);
|
||||
|
||||
if (role == 'admin') {
|
||||
var containerName = docker.getContainer(container);
|
||||
|
||||
if ((action == 'start') && (state == 'stopped')) {
|
||||
containerName.start();
|
||||
} else if ((action == 'start') && (state == 'paused')) {
|
||||
containerName.unpause();
|
||||
} else if ((action == 'stop') && (state != 'stopped')) {
|
||||
containerName.stop();
|
||||
} else if ((action == 'pause') && (state == 'running')) {
|
||||
containerName.pause();
|
||||
} else if ((action == 'pause') && (state == 'paused')) {
|
||||
containerName.unpause();
|
||||
} else if (action == 'restart') {
|
||||
containerName.restart();
|
||||
}
|
||||
} else {
|
||||
console.log('User is not an admin');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -25,7 +25,10 @@ const dockerCards = document.getElementById('cards');
|
|||
// create
|
||||
|
||||
//Update usage bars
|
||||
socket.on('metrics', ({ cpu, ram, tx, rx, disk}) => {
|
||||
socket.on('metrics', (data) => {
|
||||
|
||||
let {cpu, ram, tx, rx, disk} = data;
|
||||
|
||||
cpuText.innerHTML = `<span>CPU ${cpu} %</span>`;
|
||||
cpuBar.innerHTML = `<span style="width: ${cpu}%"><span></span></span>`;
|
||||
ramText.innerHTML = `<span>RAM ${ram} %</span>`;
|
||||
|
|
Loading…
Add table
Reference in a new issue