4
0

cacheView.html 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. {% extends 'layouts/base.html' %}
  2. {% macro flip_card(icon, title, value, back_title, description, extra_html='')%}
  3. <div class="group w-full h-48 [perspective:1000px]">
  4. <div
  5. class="relative h-full w-full rounded-xl shadow-xl transition-all duration-500 [transform-style:preserve-3d] group-hover:[transform:rotateY(180deg)]">
  6. <div
  7. class="absolute inset-0 bg-white shadow-md rounded-xl flex flex-col items-center justify-center [backface-visibility:hidden]">
  8. <i class="{{ icon }} text-3xl text-blue-600 mb-2"></i>
  9. <h3 class="text-lg font-semibold text-gray-800">{{ title }}</h3>
  10. {% if extra_html %} {{ extra_html | safe }} {% else %}
  11. <p class="text-xl text-blue-800" data-stat="{{ title|replace(' ', '_')|lower }}">
  12. {{ value }}
  13. </p>
  14. {% endif %}
  15. </div>
  16. <div class="absolute inset-0 bg-blue-600 text-white rounded-xl px-4 py-6 text-center [transform:rotateY(180deg)] [backface-visibility:hidden]">
  17. <h3 class="text-lg font-semibold mb-2">{{ back_title }}</h3>
  18. <p class="text-sm">{{ description }}</p>
  19. </div>
  20. </div>
  21. </div>
  22. {% endmacro %}
  23. {% block styles %}
  24. <script src="{{ url_for('static', filename='js/tailwindcss.js') }}"></script>
  25. <style>
  26. @keyframes progress {
  27. 0% {
  28. stroke-dasharray: 0 100;
  29. }
  30. }
  31. .circle-animation {
  32. animation: progress 1s ease-out forwards;
  33. }
  34. .main-tab-content,
  35. .tab-content {
  36. display: none;
  37. }
  38. .main-tab-content.active,
  39. .tab-content.active {
  40. display: block;
  41. animation: fadeIn 0.5s ease;
  42. }
  43. @keyframes fadeIn {
  44. from {
  45. opacity: 0;
  46. }
  47. to {
  48. opacity: 1;
  49. }
  50. }
  51. .main-tab-btn.active::after {
  52. content: "";
  53. position: absolute;
  54. bottom: 0;
  55. left: 0;
  56. right: 0;
  57. height: 3px;
  58. background-color: #3b82f6;
  59. animation: underline 0.3s ease;
  60. }
  61. @keyframes underline {
  62. from {
  63. transform: scaleX(0);
  64. }
  65. to {
  66. transform: scaleX(1);
  67. }
  68. }
  69. .value-change {
  70. animation: pulse 1s;
  71. }
  72. @keyframes pulse {
  73. 0% {
  74. transform: scale(1);
  75. }
  76. 50% {
  77. transform: scale(1.1);
  78. }
  79. 100% {
  80. transform: scale(1);
  81. }
  82. }
  83. .time-range-btn {
  84. transition: all 0.3s ease;
  85. }
  86. .time-range-btn.active {
  87. background-color: white;
  88. color: #2563eb;
  89. box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  90. }
  91. .time-range-btn:not(.active) {
  92. background-color: transparent;
  93. color: #6b7280;
  94. }
  95. .time-range-btn:not(.active):hover {
  96. color: #2563eb;
  97. }
  98. </style>
  99. {% endblock styles %}
  100. {% block content %}
  101. {% include 'partials/cache_stats.html' %}
  102. {% endblock content %}
  103. {% block scripts %}
  104. <script src="{{ url_for('static', filename='js/chart.js') }}"></script>
  105. <script src="{{ url_for('static', filename='js/chartjs-plugin-datalabels.js') }}"></script>
  106. <script>
  107. Chart.register(ChartDataLabels);
  108. let maxRamBytes = 0,
  109. maxSwapBytes = 0;
  110. const historySize = 240; // Reducido de 720 a 240 (4 horas de datos con intervalos de 1 minuto)
  111. let liveDataCounter = 0; // Contador para manejar datos en vivo
  112. // --- FUNCIONES ORIGINALES (COMPLETAS Y RESTAURADAS) ---
  113. function getLocalTimeString() {
  114. const now = new Date();
  115. let hours = now.getHours();
  116. const minutes = now.getMinutes().toString().padStart(2, "0");
  117. const ampm = hours >= 12 ? "PM" : "AM";
  118. hours = hours % 12 || 12;
  119. return `${hours}:${minutes} ${ampm}`;
  120. }
  121. function formatTime(date) {
  122. let hours = date.getHours();
  123. const minutes = date.getMinutes().toString().padStart(2, "0");
  124. const ampm = hours >= 12 ? "PM" : "AM";
  125. hours = hours % 12 || 12;
  126. return `${hours}:${minutes} ${ampm}`;
  127. }
  128. function openMainTab(tabName) {
  129. document
  130. .querySelectorAll(".main-tab-content")
  131. .forEach((content) => content.classList.remove("active"));
  132. document.querySelectorAll(".main-tab-btn").forEach((btn) => {
  133. btn.classList.remove("active", "text-blue-600");
  134. btn.classList.add("text-gray-500");
  135. });
  136. document.getElementById(tabName + "Content").classList.add("active");
  137. const tabBtn = document.getElementById(tabName + "Tab");
  138. tabBtn.classList.add("active", "text-blue-600");
  139. tabBtn.classList.remove("text-gray-500");
  140. }
  141. document
  142. .getElementById("dashboardTab")
  143. .addEventListener("click", () => openMainTab("dashboard"));
  144. document
  145. .getElementById("cacheTab")
  146. .addEventListener("click", () => openMainTab("cache"));
  147. document
  148. .getElementById("networkTab")
  149. .addEventListener("click", () => openMainTab("network"));
  150. document.querySelectorAll(".tab-btn").forEach((button, index) => {
  151. button.addEventListener("click", () => {
  152. document.querySelectorAll(".tab-btn").forEach((btn) => {
  153. btn.classList.remove(
  154. "active",
  155. "text-blue-600",
  156. "border-b-2",
  157. "border-blue-600"
  158. );
  159. btn.classList.add("text-gray-500");
  160. });
  161. button.classList.add(
  162. "active",
  163. "text-blue-600",
  164. "border-b-2",
  165. "border-blue-600"
  166. );
  167. button.classList.remove("text-gray-500");
  168. document
  169. .querySelectorAll(".tab-content")
  170. .forEach((content) => content.classList.remove("active"));
  171. document
  172. .querySelectorAll(".tab-content")
  173. [index].classList.add("active");
  174. });
  175. });
  176. const chartOptions = {
  177. responsive: true,
  178. maintainAspectRatio: false,
  179. tension: 0.3,
  180. fill: true,
  181. pointRadius: 2,
  182. scales: {
  183. x: { grid: { color: "rgba(0, 0, 0, 0.05)" } },
  184. y: { beginAtZero: true, grid: { color: "rgba(0, 0, 0, 0.05)" } },
  185. },
  186. plugins: { legend: { display: true }, datalabels: { display: false } },
  187. };
  188. const cpuChart = new Chart("cpuChart", {
  189. type: "line",
  190. data: {
  191. labels: [],
  192. datasets: [
  193. {
  194. label: "Uso de CPU (%)",
  195. data: [],
  196. borderColor: "#ef4444",
  197. backgroundColor: "rgba(239, 68, 68, 0.1)",
  198. pointBackgroundColor: "#ef4444",
  199. },
  200. ],
  201. },
  202. options: {
  203. ...chartOptions,
  204. scales: {
  205. ...chartOptions.scales,
  206. y: {
  207. ...chartOptions.scales.y,
  208. max: 100,
  209. title: { display: true, text: "%" },
  210. },
  211. },
  212. },
  213. });
  214. const ramChart = new Chart("ramChart", {
  215. type: "line",
  216. data: {
  217. labels: [],
  218. datasets: [
  219. {
  220. label: "RAM Usada",
  221. data: [],
  222. borderColor: "#3b82f6",
  223. backgroundColor: "rgba(59, 130, 246, 0.1)",
  224. pointBackgroundColor: "#3b82f6",
  225. },
  226. ],
  227. },
  228. options: {
  229. ...chartOptions,
  230. scales: {
  231. ...chartOptions.scales,
  232. y: {
  233. ...chartOptions.scales.y,
  234. title: { display: true, text: "Bytes" },
  235. ticks: { callback: formatSizeCompact },
  236. },
  237. },
  238. plugins: {
  239. ...chartOptions.plugins,
  240. tooltip: {
  241. callbacks: {
  242. label: (ctx) => "RAM Usada: " + formatSizeCompact(ctx.raw),
  243. },
  244. },
  245. },
  246. },
  247. });
  248. const swapChart = new Chart("swapChart", {
  249. type: "line",
  250. data: {
  251. labels: [],
  252. datasets: [
  253. {
  254. label: {{ _('Swap Usada') | tojson }},
  255. data: [],
  256. borderColor: "#10b981",
  257. backgroundColor: "rgba(16, 185, 129, 0.1)",
  258. pointBackgroundColor: "#10b981",
  259. },
  260. ],
  261. },
  262. options: {
  263. ...chartOptions,
  264. scales: {
  265. ...chartOptions.scales,
  266. y: {
  267. ...chartOptions.scales.y,
  268. title: { display: true, text: "Bytes" },
  269. ticks: { callback: formatSizeCompact },
  270. },
  271. },
  272. plugins: {
  273. ...chartOptions.plugins,
  274. tooltip: {
  275. callbacks: {
  276. label: (ctx) => {{ _('SWAP Usada: ') | tojson }} + formatSizeCompact(ctx.raw),
  277. },
  278. },
  279. },
  280. },
  281. });
  282. const networkChart = new Chart("networkChart", {
  283. type: "line",
  284. data: {
  285. labels: [],
  286. datasets: [
  287. {
  288. label: "Subida (Mbps)",
  289. data: [],
  290. borderColor: "#06b6d4",
  291. backgroundColor: "rgba(6,182,212,0.1)",
  292. pointBackgroundColor: "#06b6d4",
  293. },
  294. {
  295. label: "Bajada (Mbps)",
  296. data: [],
  297. borderColor: "#f59e42",
  298. backgroundColor: "rgba(245,158,66,0.1)",
  299. pointBackgroundColor: "#f59e42",
  300. },
  301. ],
  302. },
  303. options: {
  304. ...chartOptions,
  305. scales: {
  306. ...chartOptions.scales,
  307. y: {
  308. ...chartOptions.scales.y,
  309. title: { display: true, text: "Mbps" },
  310. },
  311. },
  312. },
  313. });
  314. function formatSizeCompact(bytes) {
  315. if (bytes === 0) return "0 B";
  316. const units = ["B", "KB", "MB", "GB"];
  317. const i = Math.floor(Math.log(bytes) / Math.log(1024));
  318. return `${parseFloat(
  319. (bytes / Math.pow(1024, i)).toFixed(i === 0 ? 0 : 1)
  320. )} ${units[i]}`;
  321. }
  322. function parseSize(sizeStr) {
  323. if (!sizeStr) return { value: 0, unit: "B" };
  324. const parts = sizeStr.trim().split(" ");
  325. return {
  326. value: parseFloat(parts[0]) || 0,
  327. unit: parts.length > 1 ? parts[1].charAt(0) : "B",
  328. };
  329. }
  330. function sizeToBytes(sizeStr) {
  331. const { value, unit } = parseSize(sizeStr);
  332. const multipliers = { G: 1024 * 1024 * 1024, M: 1024 * 1024, K: 1024 };
  333. return value * (multipliers[unit] || 1);
  334. }
  335. function updateRings(info) {
  336. const cpuPercent = parseFloat(info.cpu.usage.replace("%", ""));
  337. document
  338. .getElementById("cpu-ring")
  339. .setAttribute("stroke-dasharray", `${cpuPercent},100`);
  340. document.getElementById(
  341. "cpu-value"
  342. ).textContent = `${cpuPercent.toFixed(1)}%`;
  343. const ramUsedInfo = parseSize(info.ram.used);
  344. document.getElementById(
  345. "ram-used"
  346. ).textContent = `${ramUsedInfo.value.toFixed(1)}${ramUsedInfo.unit}`;
  347. document
  348. .getElementById("ram-ring")
  349. .setAttribute(
  350. "stroke-dasharray",
  351. `${parseFloat(info.ram.percent.replace("%", ""))},100`
  352. );
  353. const swapUsedInfo = parseSize(info.swap.used);
  354. document.getElementById(
  355. "swap-used"
  356. ).textContent = `${swapUsedInfo.value.toFixed(1)}${swapUsedInfo.unit}`;
  357. document
  358. .getElementById("swap-ring")
  359. .setAttribute(
  360. "stroke-dasharray",
  361. `${parseFloat(info.swap.percent.replace("%", "") || 0)},100`
  362. );
  363. }
  364. function updateSystemInfo(info) {
  365. document.getElementById("hostname").textContent = info.hostname;
  366. document.getElementById("ip-addresses").innerHTML = info.ips
  367. .map((ip) => ip.ip)
  368. .join("<br>");
  369. document.getElementById("os-info").textContent = info.os;
  370. document.getElementById("uptime").textContent = info.uptime;
  371. document.getElementById("local-time").textContent = info.local_time;
  372. }
  373. function updateCard(statId, value, isSize = false) {
  374. const element = document.querySelector(`[data-stat="${statId}"]`);
  375. if (!element) return;
  376. let formattedValue = value;
  377. if (isSize) {
  378. const bytes = parseFloat(value);
  379. formattedValue =
  380. bytes / (1024 * 1024) < 1
  381. ? `${Math.round(bytes / 1024)} MB`
  382. : `${(bytes / (1024 * 1024)).toFixed(2)} GB`;
  383. }
  384. if (element.textContent !== formattedValue.toString()) {
  385. element.textContent = formattedValue;
  386. element.classList.add("value-change");
  387. setTimeout(() => element.classList.remove("value-change"), 1000);
  388. }
  389. }
  390. function updateCacheStats(stats) {
  391. updateCard("entradas_almacenadas", stats.store_entries);
  392. updateCard("uso_de_capacidad", stats.capacity_used);
  393. updateCard("espacio_total", stats.fs_space_total, true);
  394. updateCard("espacio_usado", stats.fs_space_used, true);
  395. updateCard("eliminación", stats.removal_policy);
  396. updateCard("edad_lru", `${stats.lru_age_days} días`);
  397. }
  398. // --- AÑADIDO: Carga de datos históricos desde la API con sampling optimizado ---
  399. function loadHistoricData(endpoint = "/api/metrics/24hours") {
  400. fetch(endpoint)
  401. .then((response) => response.json())
  402. .then((data) => {
  403. if (!data || data.length === 0) {
  404. return;
  405. }
  406. // Implementar sampling inteligente para evitar sobrecarga
  407. let sampledData = data;
  408. if (data.length > 288) {
  409. // Si hay más de 288 puntos (4.8 horas con intervalos de 1 minuto)
  410. const sampleRate = Math.ceil(data.length / 288);
  411. sampledData = data.filter((_, index) => index % sampleRate === 0);
  412. }
  413. const labels = [],
  414. cpuData = [],
  415. ramData = [],
  416. swapData = [],
  417. netUpData = [],
  418. netDownData = [];
  419. sampledData.forEach((metric) => {
  420. // Crear fecha local desde el timestamp del servidor (ya incluye timezone)
  421. const localDate = new Date(metric.timestamp);
  422. labels.push(formatTime(localDate));
  423. cpuData.push(parseFloat(metric.cpu_usage).toFixed(1));
  424. ramData.push(metric.ram_usage_bytes);
  425. swapData.push(metric.swap_usage_bytes);
  426. netUpData.push(
  427. ((metric.net_sent_bytes_sec * 8) / 1000000).toFixed(2)
  428. );
  429. netDownData.push(
  430. ((metric.net_recv_bytes_sec * 8) / 1000000).toFixed(2)
  431. );
  432. });
  433. const charts = [cpuChart, ramChart, swapChart, networkChart];
  434. const chartData = [
  435. cpuData,
  436. ramData,
  437. swapData,
  438. [netUpData, netDownData],
  439. ];
  440. charts.forEach((chart, chartIndex) => {
  441. chart.data.labels = [...labels];
  442. if (chartIndex === 3) {
  443. chart.data.datasets[0].data = chartData[chartIndex][0];
  444. chart.data.datasets[1].data = chartData[chartIndex][1];
  445. } else {
  446. chart.data.datasets[0].data = chartData[chartIndex];
  447. }
  448. chart.update();
  449. });
  450. })
  451. .catch((error) =>
  452. console.error("Error al cargar historial de métricas:", error)
  453. );
  454. }
  455. // --- AÑADIDO: Funcionalidad para alternar entre vistas de tiempo ---
  456. function setupTimeRangeButtons() {
  457. const todayBtn = document.getElementById("todayBtn");
  458. const hoursBtn = document.getElementById("24hoursBtn");
  459. todayBtn.addEventListener("click", () => {
  460. setActiveTimeRange(todayBtn, hoursBtn);
  461. loadHistoricData("/api/metrics/today");
  462. });
  463. hoursBtn.addEventListener("click", () => {
  464. setActiveTimeRange(hoursBtn, todayBtn);
  465. loadHistoricData("/api/metrics/24hours");
  466. });
  467. }
  468. function setActiveTimeRange(activeBtn, inactiveBtn) {
  469. activeBtn.classList.add("active");
  470. activeBtn.classList.remove("text-gray-500");
  471. activeBtn.classList.add("text-blue-600", "bg-white", "shadow");
  472. inactiveBtn.classList.remove("active");
  473. inactiveBtn.classList.add("text-gray-500");
  474. inactiveBtn.classList.remove("text-blue-600", "bg-white", "shadow");
  475. }
  476. const socket = io();
  477. socket.on("system_update", function (data) {
  478. updateRings(data.system_info);
  479. updateSystemInfo(data.system_info);
  480. updateCacheStats(data.cache_stats);
  481. // Incrementar contador de datos en vivo
  482. liveDataCounter++;
  483. // Solo actualizar gráficas cada 4 actualizaciones (1 minuto) para evitar sobrecarga
  484. if (liveDataCounter % 4 === 0) {
  485. // --- MODIFICADO: Lógica para añadir datos en vivo a las gráficas ---
  486. function appendLiveData(chart, label, newData) {
  487. chart.data.labels.push(label);
  488. chart.data.datasets.forEach((dataset, index) => {
  489. const dataPoint = Array.isArray(newData)
  490. ? newData[index]
  491. : newData;
  492. dataset.data.push(dataPoint);
  493. });
  494. while (chart.data.labels.length > historySize) {
  495. chart.data.labels.shift();
  496. chart.data.datasets.forEach((dataset) => dataset.data.shift());
  497. }
  498. chart.update("none");
  499. }
  500. // --- CORREGIDO: Se usa la hora local del cliente para la etiqueta en vivo ---
  501. const newLabel = getLocalTimeString();
  502. appendLiveData(
  503. cpuChart,
  504. newLabel,
  505. parseFloat(data.system_info.cpu.usage.replace("%", ""))
  506. );
  507. appendLiveData(
  508. ramChart,
  509. newLabel,
  510. sizeToBytes(data.system_info.ram.used)
  511. );
  512. appendLiveData(
  513. swapChart,
  514. newLabel,
  515. sizeToBytes(data.system_info.swap.used)
  516. );
  517. if (data.network_stats) {
  518. appendLiveData(networkChart, newLabel, [
  519. data.network_stats.up_mbps,
  520. data.network_stats.down_mbps,
  521. ]);
  522. }
  523. }
  524. });
  525. document.addEventListener("DOMContentLoaded", function () {
  526. maxRamBytes = sizeToBytes("{{ system_info.ram.total }}");
  527. maxSwapBytes = sizeToBytes("{{ system_info.swap.total }}");
  528. ramChart.options.scales.y.max = maxRamBytes;
  529. swapChart.options.scales.y.max = maxSwapBytes;
  530. updateRings({
  531. cpu: {
  532. usage: "{{ system_info.cpu.usage }}",
  533. percent: "{{ system_info.cpu.usage }}",
  534. },
  535. ram: {
  536. used: "{{ system_info.ram.used }}",
  537. percent: "{{ system_info.ram.percent }}",
  538. },
  539. swap: {
  540. used: "{{ system_info.swap.used }}",
  541. percent: "{{ system_info.swap.percent }}",
  542. },
  543. });
  544. // Inicializar botones de rango de tiempo
  545. setupTimeRangeButtons();
  546. // Cargar datos históricos (por defecto 24 horas)
  547. loadHistoricData("/api/metrics/24hours");
  548. });
  549. </script>
  550. {% endblock scripts %}