Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let cpuChart, ramChart, diskChart, networkUpChart, networkDownChart, uptimeChart;
- document.addEventListener('DOMContentLoaded', function() {
- console.log('Current Status Data:', window.currentStatusData);
- console.log('Historical Status Data:', window.historicalStatusData);
- renderCharts();
- setInterval(refreshCharts, 1000); // Refresh CPU, RAM, Disk, and Uptime charts every second
- setInterval(fetchAndRenderNetworkData, 60000); // Refresh Network charts every minute
- });
- function renderCharts() {
- // Ensure currentStatusData is an array and has at least one element
- const currentStatus = Array.isArray(window.currentStatusData) ? window.currentStatusData : [];
- if (currentStatus.length === 0) {
- console.error('Current status data is empty or not an array');
- return;
- }
- // Ensure historicalStatusData is an array
- const historicalStatus = Array.isArray(window.historicalStatusData) ? window.historicalStatusData : [];
- if (historicalStatus.length === 0) {
- console.error('Historical status data is empty or not an array');
- return;
- }
- // Parse numeric values from strings if necessary
- const parsedCurrentStatus = currentStatus.map(status => ({
- ...status,
- cpu_usage: parseFloat(status.cpu_usage),
- ram_usage: parseFloat(status.ram_usage),
- disk_usage: parseFloat(status.disk_usage),
- network_up: parseFloat(status.network_up),
- network_down: parseFloat(status.network_down)
- }));
- // Calculate averages and percentages as needed
- const avgRamUsage = calculateAverageRamUsage(parsedCurrentStatus);
- const avgDiskUsage = calculateAverageDiskUsage(parsedCurrentStatus);
- const uptimePercentage = calculateUptimePercentage(historicalStatus);
- // Render charts
- cpuChart = renderCpuChart(parsedCurrentStatus[0].cpu_usage);
- ramChart = renderRamChart(avgRamUsage);
- diskChart = renderDiskChart(parsedCurrentStatus);
- networkUpChart = renderNetworkChart(parsedCurrentStatus, 'networkOutChart');
- networkDownChart = renderNetworkChart(parsedCurrentStatus, 'networkInChart');
- uptimeChart = renderUptimeChart(uptimePercentage);
- }
- function renderCpuChart(cpuUsage) {
- const ctx = document.getElementById('cpuChart').getContext('2d');
- new Chart(ctx, {
- type: 'doughnut',
- data: {
- datasets: [{
- data: [cpuUsage, 100 - cpuUsage],
- backgroundColor: [
- cpuUsage > 90 ? 'rgb(66,66,66)' : cpuUsage > 75 ? 'red' : 'rgb(255,140,25)',
- 'rgb(0,184,184)'
- ],
- borderWidth: 0
- }]
- },
- options: {
- rotation: -90,
- circumference: 180,
- cutoutPercentage: 75,
- maintainAspectRatio: false,
- responsive: true,
- legend: {
- display: false
- },
- plugins: {
- tooltip: {
- callbacks: {
- footer: function(tooltipItems) {
- let label = tooltipItems[0].parsed;
- if (tooltipItems[0].dataIndex === 0) {
- return `${label.toFixed(2)}% Used`;
- } else {
- return `${label.toFixed(2)}% Free`;
- }
- }
- }
- }
- },
- animation: {
- animateRotate: true
- }
- }
- });
- }
- function renderRamChart(ramUsage) {
- const ctx = document.getElementById('ramChart').getContext('2d');
- new Chart(ctx, {
- type: 'doughnut',
- data: {
- datasets: [{
- data: [ramUsage, 100 - ramUsage],
- backgroundColor: [
- ramUsage > 90 ? 'rgb(66,66,66)' : ramUsage > 75 ? 'red' : 'rgb(255,140,25)',
- 'rgb(0,184,184)'
- ],
- borderWidth: 0
- }]
- },
- options: {
- rotation: -90, // Start from top
- circumference: 180, // Half circle
- cutoutPercentage: 75, // Adjust for gauge thickness
- maintainAspectRatio: false,
- responsive: true,
- legend: {
- display: false
- },
- plugins: {
- tooltip: {
- callbacks: {
- footer: function(tooltipItems) {
- let label = tooltipItems[0].parsed;
- if (tooltipItems[0].dataIndex === 0) {
- return `${label.toFixed(2)}% Used`;
- } else {
- return `${label.toFixed(2)}% Free`;
- }
- }
- }
- }
- },
- animation: {
- animateRotate: true
- }
- }
- });
- }
- function renderDiskChart(currentStatus) {
- // Calculate the average disk usage
- const totalDiskUsage = currentStatus.reduce((acc, server) => acc + server.disk_usage, 0);
- const avgDiskUsage = Math.round(totalDiskUsage / currentStatus.length);
- const avgDiskFree = 100 - avgDiskUsage; // Calculate free disk space
- const ctx = document.getElementById('diskChart').getContext('2d');
- new Chart(ctx, {
- type: 'bar',
- data: {
- labels: ['Disk'],
- datasets: [
- {
- label: 'Used',
- data: [avgDiskUsage],
- backgroundColor: avgDiskUsage > 90 ? 'rgb(66,66,66)' : avgDiskUsage > 75 ? 'red' : 'rgb(255,140,25)',
- },
- {
- label: 'Free',
- data: [avgDiskFree],
- backgroundColor: 'rgb(0,184,184)',
- }
- ]
- },
- options: {
- scales: {
- x: {
- display: false
- },
- y: {
- beginAtZero: true,
- max: 100,
- ticks: {
- stepSize: 100,
- color: '#444'
- },
- grid: {
- display: true,
- drawBorder: false,
- drawOnChartArea: true,
- drawTicks: false,
- color: function(context) {
- if (context.tick.value === 0 || context.tick.value === 100) {
- return '#444';
- }
- return 'transparent';
- }
- }
- }
- },
- plugins: {
- legend: {
- display: false
- },
- tooltip: {
- callbacks: {
- label: function(context) {
- let label = context.dataset.label;
- let value = context.raw;
- return `${label}: ${value}%`;
- }
- }
- }
- },
- maintainAspectRatio: false,
- responsive: true,
- animation: {
- animateScale: true
- }
- }
- });
- }
- function convertBytesToMbps(bytes) {
- return (bytes * 8) / (10 ** 6);
- }
- function renderNetworkChart(currentStatus, chartId) {
- const ctx = document.getElementById(chartId).getContext('2d');
- const networkData = currentStatus.map(server => convertBytesToMbps(server[chartId === 'networkOutChart' ? 'network_up' : 'network_down']));
- return new Chart(ctx, {
- type: 'line',
- data: {
- labels: currentStatus.map((_, index) => `Reading ${index + 1}`),
- datasets: [{
- label: chartId === 'networkOutChart' ? 'Outgoing Network Data (Mbps)' : 'Incoming Network Data (Mbps)',
- data: networkData,
- fill: false,
- borderColor: chartId === 'networkOutChart' ? 'rgb(0,179,179)' : 'rgb(255,140,25)'
- }]
- },
- options: {
- scales: {
- x: {
- display: true
- },
- y: {
- beginAtZero: true
- }
- },
- maintainAspectRatio: true,
- responsive: true
- }
- });
- }
- function renderUptimeChart(uptimePercentage) {
- const ctx = document.getElementById('uptimeChart').getContext('2d');
- new Chart(ctx, {
- type: 'doughnut',
- data: {
- datasets: [{
- data: [uptimePercentage, 100 - uptimePercentage],
- backgroundColor: ['green', 'transparent']
- }]
- }
- });
- }
- function fetchAndRenderNetworkData() {
- fetch('/network-data-last-30-minutes')
- .then(response => response.json())
- .then(data => {
- // Assuming data is an array of objects with network_up and network_down properties
- const networkUpData = data.map(server => convertBytesToMbps(server.network_up));
- const networkDownData = data.map(server => convertBytesToMbps(server.network_down));
- // Update the datasets for both charts
- networkUpChart.data.datasets[0].data = networkUpData;
- networkDownChart.data.datasets[0].data = networkDownData;
- // Update the labels if necessary
- // For example, if you want to show timestamps as labels
- networkUpChart.data.labels = data.map(server => new Date(server.recorded_at).toLocaleTimeString());
- networkDownChart.data.labels = data.map(server => new Date(server.recorded_at).toLocaleTimeString());
- // Update the charts to reflect the new data
- networkUpChart.update();
- networkDownChart.update();
- })
- .catch(error => console.error('Error fetching network data:', error));
- }
- document.addEventListener('DOMContentLoaded', function() {
- refreshCharts();
- });
- function refreshCharts() {
- fetch('/current-status')
- .then(response => response.json())
- .then(currentStatus => {
- // Update CPU chart
- cpuChart.data.datasets[0].data = [currentStatus[0].cpu_usage, 100 - currentStatus[0].cpu_usage];
- cpuChart.update();
- // Update RAM chart
- const avgRamUsage = calculateAverageRamUsage(currentStatus);
- ramChart.data.datasets[0].data = [avgRamUsage, 100 - avgRamUsage];
- ramChart.update();
- // Update Disk chart
- const avgDiskUsage = calculateAverageDiskUsage(currentStatus);
- diskChart.data.datasets[0].data = [avgDiskUsage];
- diskChart.data.datasets[1].data = [100 - avgDiskUsage];
- diskChart.update();
- })
- .catch(error => console.error('Error fetching current status:', error));
- }
- function calculateAverageDiskUsage(currentStatus) {
- const totalDiskUsage = currentStatus.reduce((acc, server) => acc + server.disk_usage, 0);
- return Math.round(totalDiskUsage / currentStatus.length);
- }
- function calculateAverageRamUsage(currentStatus) {
- const totalRamUsage = currentStatus.reduce((acc, server) => acc + server.ram_usage, 0);
- return totalRamUsage / currentStatus.length;
- }
- function calculateUptimePercentage(historicalStatus) {
- const onlineCount = historicalStatus.filter(data => data.uptime_status === 'online').length;
- return (onlineCount / historicalStatus.length) * 100;
- }
Advertisement
Add Comment
Please, Sign In to add comment