Guest User

Untitled

a guest
Jan 2nd, 2024
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.79 KB | None | 0 0
  1. let cpuChart, ramChart, diskChart, networkUpChart, networkDownChart, uptimeChart;
  2.  
  3. document.addEventListener('DOMContentLoaded', function() {
  4. console.log('Current Status Data:', window.currentStatusData);
  5. console.log('Historical Status Data:', window.historicalStatusData);
  6. renderCharts();
  7. setInterval(refreshCharts, 1000); // Refresh CPU, RAM, Disk, and Uptime charts every second
  8. setInterval(fetchAndRenderNetworkData, 60000); // Refresh Network charts every minute
  9. });
  10.  
  11. function renderCharts() {
  12. // Ensure currentStatusData is an array and has at least one element
  13. const currentStatus = Array.isArray(window.currentStatusData) ? window.currentStatusData : [];
  14. if (currentStatus.length === 0) {
  15. console.error('Current status data is empty or not an array');
  16. return;
  17. }
  18.  
  19. // Ensure historicalStatusData is an array
  20. const historicalStatus = Array.isArray(window.historicalStatusData) ? window.historicalStatusData : [];
  21. if (historicalStatus.length === 0) {
  22. console.error('Historical status data is empty or not an array');
  23. return;
  24. }
  25.  
  26. // Parse numeric values from strings if necessary
  27. const parsedCurrentStatus = currentStatus.map(status => ({
  28. ...status,
  29. cpu_usage: parseFloat(status.cpu_usage),
  30. ram_usage: parseFloat(status.ram_usage),
  31. disk_usage: parseFloat(status.disk_usage),
  32. network_up: parseFloat(status.network_up),
  33. network_down: parseFloat(status.network_down)
  34. }));
  35.  
  36. // Calculate averages and percentages as needed
  37. const avgRamUsage = calculateAverageRamUsage(parsedCurrentStatus);
  38. const avgDiskUsage = calculateAverageDiskUsage(parsedCurrentStatus);
  39. const uptimePercentage = calculateUptimePercentage(historicalStatus);
  40.  
  41. // Render charts
  42. cpuChart = renderCpuChart(parsedCurrentStatus[0].cpu_usage);
  43. ramChart = renderRamChart(avgRamUsage);
  44. diskChart = renderDiskChart(parsedCurrentStatus);
  45. networkUpChart = renderNetworkChart(parsedCurrentStatus, 'networkOutChart');
  46. networkDownChart = renderNetworkChart(parsedCurrentStatus, 'networkInChart');
  47. uptimeChart = renderUptimeChart(uptimePercentage);
  48. }
  49. function renderCpuChart(cpuUsage) {
  50. const ctx = document.getElementById('cpuChart').getContext('2d');
  51. new Chart(ctx, {
  52. type: 'doughnut',
  53. data: {
  54. datasets: [{
  55. data: [cpuUsage, 100 - cpuUsage],
  56. backgroundColor: [
  57. cpuUsage > 90 ? 'rgb(66,66,66)' : cpuUsage > 75 ? 'red' : 'rgb(255,140,25)',
  58. 'rgb(0,184,184)'
  59. ],
  60. borderWidth: 0
  61. }]
  62. },
  63. options: {
  64. rotation: -90,
  65. circumference: 180,
  66. cutoutPercentage: 75,
  67. maintainAspectRatio: false,
  68. responsive: true,
  69. legend: {
  70. display: false
  71. },
  72. plugins: {
  73. tooltip: {
  74. callbacks: {
  75. footer: function(tooltipItems) {
  76. let label = tooltipItems[0].parsed;
  77. if (tooltipItems[0].dataIndex === 0) {
  78. return `${label.toFixed(2)}% Used`;
  79. } else {
  80. return `${label.toFixed(2)}% Free`;
  81. }
  82. }
  83. }
  84. }
  85. },
  86. animation: {
  87. animateRotate: true
  88. }
  89. }
  90. });
  91. }
  92.  
  93. function renderRamChart(ramUsage) {
  94. const ctx = document.getElementById('ramChart').getContext('2d');
  95. new Chart(ctx, {
  96. type: 'doughnut',
  97. data: {
  98. datasets: [{
  99. data: [ramUsage, 100 - ramUsage],
  100. backgroundColor: [
  101. ramUsage > 90 ? 'rgb(66,66,66)' : ramUsage > 75 ? 'red' : 'rgb(255,140,25)',
  102. 'rgb(0,184,184)'
  103. ],
  104. borderWidth: 0
  105. }]
  106. },
  107. options: {
  108. rotation: -90, // Start from top
  109. circumference: 180, // Half circle
  110. cutoutPercentage: 75, // Adjust for gauge thickness
  111. maintainAspectRatio: false,
  112. responsive: true,
  113. legend: {
  114. display: false
  115. },
  116. plugins: {
  117. tooltip: {
  118. callbacks: {
  119. footer: function(tooltipItems) {
  120. let label = tooltipItems[0].parsed;
  121. if (tooltipItems[0].dataIndex === 0) {
  122. return `${label.toFixed(2)}% Used`;
  123. } else {
  124. return `${label.toFixed(2)}% Free`;
  125. }
  126. }
  127. }
  128. }
  129. },
  130. animation: {
  131. animateRotate: true
  132. }
  133. }
  134. });
  135. }
  136.  
  137. function renderDiskChart(currentStatus) {
  138. // Calculate the average disk usage
  139. const totalDiskUsage = currentStatus.reduce((acc, server) => acc + server.disk_usage, 0);
  140. const avgDiskUsage = Math.round(totalDiskUsage / currentStatus.length);
  141. const avgDiskFree = 100 - avgDiskUsage; // Calculate free disk space
  142.  
  143. const ctx = document.getElementById('diskChart').getContext('2d');
  144. new Chart(ctx, {
  145. type: 'bar',
  146. data: {
  147. labels: ['Disk'],
  148. datasets: [
  149. {
  150. label: 'Used',
  151. data: [avgDiskUsage],
  152. backgroundColor: avgDiskUsage > 90 ? 'rgb(66,66,66)' : avgDiskUsage > 75 ? 'red' : 'rgb(255,140,25)',
  153. },
  154. {
  155. label: 'Free',
  156. data: [avgDiskFree],
  157. backgroundColor: 'rgb(0,184,184)',
  158. }
  159. ]
  160. },
  161. options: {
  162. scales: {
  163. x: {
  164. display: false
  165. },
  166. y: {
  167. beginAtZero: true,
  168. max: 100,
  169. ticks: {
  170. stepSize: 100,
  171. color: '#444'
  172. },
  173. grid: {
  174. display: true,
  175. drawBorder: false,
  176. drawOnChartArea: true,
  177. drawTicks: false,
  178. color: function(context) {
  179. if (context.tick.value === 0 || context.tick.value === 100) {
  180. return '#444';
  181. }
  182. return 'transparent';
  183. }
  184. }
  185. }
  186. },
  187. plugins: {
  188. legend: {
  189. display: false
  190. },
  191. tooltip: {
  192. callbacks: {
  193. label: function(context) {
  194. let label = context.dataset.label;
  195. let value = context.raw;
  196. return `${label}: ${value}%`;
  197. }
  198. }
  199. }
  200. },
  201. maintainAspectRatio: false,
  202. responsive: true,
  203. animation: {
  204. animateScale: true
  205. }
  206. }
  207. });
  208. }
  209.  
  210. function convertBytesToMbps(bytes) {
  211. return (bytes * 8) / (10 ** 6);
  212. }
  213.  
  214. function renderNetworkChart(currentStatus, chartId) {
  215. const ctx = document.getElementById(chartId).getContext('2d');
  216. const networkData = currentStatus.map(server => convertBytesToMbps(server[chartId === 'networkOutChart' ? 'network_up' : 'network_down']));
  217.  
  218. return new Chart(ctx, {
  219. type: 'line',
  220. data: {
  221. labels: currentStatus.map((_, index) => `Reading ${index + 1}`),
  222. datasets: [{
  223. label: chartId === 'networkOutChart' ? 'Outgoing Network Data (Mbps)' : 'Incoming Network Data (Mbps)',
  224. data: networkData,
  225. fill: false,
  226. borderColor: chartId === 'networkOutChart' ? 'rgb(0,179,179)' : 'rgb(255,140,25)'
  227. }]
  228. },
  229. options: {
  230. scales: {
  231. x: {
  232. display: true
  233. },
  234. y: {
  235. beginAtZero: true
  236. }
  237. },
  238. maintainAspectRatio: true,
  239. responsive: true
  240. }
  241. });
  242. }
  243.  
  244. function renderUptimeChart(uptimePercentage) {
  245. const ctx = document.getElementById('uptimeChart').getContext('2d');
  246. new Chart(ctx, {
  247. type: 'doughnut',
  248. data: {
  249. datasets: [{
  250. data: [uptimePercentage, 100 - uptimePercentage],
  251. backgroundColor: ['green', 'transparent']
  252. }]
  253. }
  254. });
  255. }
  256.  
  257. function fetchAndRenderNetworkData() {
  258. fetch('/network-data-last-30-minutes')
  259. .then(response => response.json())
  260. .then(data => {
  261. // Assuming data is an array of objects with network_up and network_down properties
  262. const networkUpData = data.map(server => convertBytesToMbps(server.network_up));
  263. const networkDownData = data.map(server => convertBytesToMbps(server.network_down));
  264.  
  265. // Update the datasets for both charts
  266. networkUpChart.data.datasets[0].data = networkUpData;
  267. networkDownChart.data.datasets[0].data = networkDownData;
  268.  
  269. // Update the labels if necessary
  270. // For example, if you want to show timestamps as labels
  271. networkUpChart.data.labels = data.map(server => new Date(server.recorded_at).toLocaleTimeString());
  272. networkDownChart.data.labels = data.map(server => new Date(server.recorded_at).toLocaleTimeString());
  273.  
  274. // Update the charts to reflect the new data
  275. networkUpChart.update();
  276. networkDownChart.update();
  277. })
  278. .catch(error => console.error('Error fetching network data:', error));
  279. }
  280.  
  281. document.addEventListener('DOMContentLoaded', function() {
  282. refreshCharts();
  283. });
  284.  
  285. function refreshCharts() {
  286. fetch('/current-status')
  287. .then(response => response.json())
  288. .then(currentStatus => {
  289. // Update CPU chart
  290. cpuChart.data.datasets[0].data = [currentStatus[0].cpu_usage, 100 - currentStatus[0].cpu_usage];
  291. cpuChart.update();
  292.  
  293. // Update RAM chart
  294. const avgRamUsage = calculateAverageRamUsage(currentStatus);
  295. ramChart.data.datasets[0].data = [avgRamUsage, 100 - avgRamUsage];
  296. ramChart.update();
  297.  
  298. // Update Disk chart
  299. const avgDiskUsage = calculateAverageDiskUsage(currentStatus);
  300. diskChart.data.datasets[0].data = [avgDiskUsage];
  301. diskChart.data.datasets[1].data = [100 - avgDiskUsage];
  302. diskChart.update();
  303. })
  304. .catch(error => console.error('Error fetching current status:', error));
  305. }
  306.  
  307. function calculateAverageDiskUsage(currentStatus) {
  308. const totalDiskUsage = currentStatus.reduce((acc, server) => acc + server.disk_usage, 0);
  309. return Math.round(totalDiskUsage / currentStatus.length);
  310. }
  311.  
  312. function calculateAverageRamUsage(currentStatus) {
  313. const totalRamUsage = currentStatus.reduce((acc, server) => acc + server.ram_usage, 0);
  314. return totalRamUsage / currentStatus.length;
  315. }
  316.  
  317. function calculateUptimePercentage(historicalStatus) {
  318. const onlineCount = historicalStatus.filter(data => data.uptime_status === 'online').length;
  319. return (onlineCount / historicalStatus.length) * 100;
  320. }
  321.  
Advertisement
Add Comment
Please, Sign In to add comment