cacheView.html 18 KB

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