cache_stats.html 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  1. {% macro flip_card(icon, title, value, back_title, description, extra_html='')
  2. %}
  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. >
  7. <div
  8. class="absolute inset-0 bg-white shadow-md rounded-xl flex flex-col items-center justify-center [backface-visibility:hidden]"
  9. >
  10. <i class="{{ icon }} text-3xl text-blue-600 mb-2"></i>
  11. <h3 class="text-lg font-semibold text-gray-800">{{ title }}</h3>
  12. {% if extra_html %} {{ extra_html | safe }} {% else %}
  13. <p
  14. class="text-xl text-blue-800"
  15. data-stat="{{ title|replace(' ', '_')|lower }}"
  16. >
  17. {{ value }}
  18. </p>
  19. {% endif %}
  20. </div>
  21. <div
  22. class="absolute inset-0 bg-blue-600 text-white rounded-xl px-4 py-6 text-center [transform:rotateY(180deg)] [backface-visibility:hidden]"
  23. >
  24. <h3 class="text-lg font-semibold mb-2">{{ back_title }}</h3>
  25. <p class="text-sm">{{ description }}</p>
  26. </div>
  27. </div>
  28. </div>
  29. {% endmacro %}
  30. <!DOCTYPE html>
  31. <html lang="es">
  32. <head>
  33. <meta charset="UTF-8" />
  34. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  35. <title>Dashboard de Sistema</title>
  36. <link
  37. rel="icon"
  38. href="{{ url_for('static', filename=page_icon) }}"
  39. type="image/x-icon"
  40. />
  41. <script src="{{ url_for('static', filename='js/tailwindcss.js') }}"></script>
  42. <link
  43. rel="stylesheet"
  44. href="{{ url_for('static', filename='all.min.css') }}"
  45. />
  46. <script src="{{ url_for('static', filename='js/chart.js') }}"></script>
  47. <script src="{{ url_for('static', filename='js/chartjs-plugin-datalabels.js') }}"></script>
  48. <script src="{{ url_for('static', filename='js/socket.io.min.js') }}"></script>
  49. <style>
  50. @keyframes progress {
  51. 0% {
  52. stroke-dasharray: 0 100;
  53. }
  54. }
  55. .circle-animation {
  56. animation: progress 1s ease-out forwards;
  57. }
  58. .main-tab-content,
  59. .tab-content {
  60. display: none;
  61. }
  62. .main-tab-content.active,
  63. .tab-content.active {
  64. display: block;
  65. animation: fadeIn 0.5s ease;
  66. }
  67. @keyframes fadeIn {
  68. from {
  69. opacity: 0;
  70. }
  71. to {
  72. opacity: 1;
  73. }
  74. }
  75. .main-tab-btn.active::after {
  76. content: "";
  77. position: absolute;
  78. bottom: 0;
  79. left: 0;
  80. right: 0;
  81. height: 3px;
  82. background-color: #3b82f6;
  83. animation: underline 0.3s ease;
  84. }
  85. @keyframes underline {
  86. from {
  87. transform: scaleX(0);
  88. }
  89. to {
  90. transform: scaleX(1);
  91. }
  92. }
  93. .value-change {
  94. animation: pulse 1s;
  95. }
  96. @keyframes pulse {
  97. 0% {
  98. transform: scale(1);
  99. }
  100. 50% {
  101. transform: scale(1.1);
  102. }
  103. 100% {
  104. transform: scale(1);
  105. }
  106. }
  107. .time-range-btn {
  108. transition: all 0.3s ease;
  109. }
  110. .time-range-btn.active {
  111. background-color: white;
  112. color: #2563eb;
  113. box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  114. }
  115. .time-range-btn:not(.active) {
  116. background-color: transparent;
  117. color: #6b7280;
  118. }
  119. .time-range-btn:not(.active):hover {
  120. color: #2563eb;
  121. }
  122. </style>
  123. </head>
  124. <body class="bg-gray-50">
  125. <div class="max-w-7xl mx-auto px-4 py-8">
  126. <h1 class="text-3xl font-bold text-center text-gray-800 mb-8">
  127. Dashboard de Estadísticas del Sistema
  128. </h1>
  129. <div class="flex border-b mb-6">
  130. <button
  131. id="dashboardTab"
  132. class="main-tab-btn active relative overflow-hidden py-3 px-6 font-medium text-blue-600"
  133. >
  134. <i class="fas fa-tachometer-alt mr-2"></i>Dashboard del Sistema
  135. </button>
  136. <button
  137. id="cacheTab"
  138. class="main-tab-btn relative overflow-hidden py-3 px-6 font-medium text-gray-500 hover:text-blue-600"
  139. >
  140. <i class="fas fa-database mr-2"></i>Estadísticas de Caché
  141. </button>
  142. <button
  143. id="networkTab"
  144. class="main-tab-btn relative overflow-hidden py-3 px-6 font-medium text-gray-500 hover:text-blue-600"
  145. >
  146. <i class="fas fa-network-wired mr-2"></i>Tráfico de Red
  147. </button>
  148. </div>
  149. <div id="dashboardContent" class="main-tab-content active">
  150. <section class="mb-12">
  151. <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
  152. <div class="bg-white rounded-xl shadow-lg p-6">
  153. <div class="flex items-center mb-6">
  154. <i class="fas fa-chart-pie text-2xl text-blue-600 mr-3"></i>
  155. <h2 class="text-xl font-bold text-gray-800">
  156. Estadísticas del Sistema
  157. </h2>
  158. </div>
  159. <div
  160. class="grid grid-cols-1 md:grid-cols-3 gap-6 items-center justify-center"
  161. >
  162. <div class="flex flex-col items-center justify-center">
  163. <div class="relative w-36 h-36">
  164. <svg viewBox="0 0 36 36" class="block mx-auto">
  165. <path
  166. class="fill-none stroke-red-100 stroke-[3.5]"
  167. d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
  168. />
  169. <path
  170. id="cpu-ring"
  171. class="circle-animation fill-none stroke-linecap-round stroke-red-500 stroke-[3.5]"
  172. stroke-dasharray="0,100"
  173. d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
  174. />
  175. <text
  176. id="cpu-value"
  177. x="18"
  178. y="18"
  179. class="text-[0.5rem] fill-gray-500"
  180. text-anchor="middle"
  181. dominant-baseline="middle"
  182. >
  183. 0%
  184. </text>
  185. </svg>
  186. </div>
  187. <h3 class="mt-2 font-semibold text-gray-700">CPU</h3>
  188. <p
  189. class="text-xs mt-1 bg-red-500 text-white px-2 py-0.5 rounded-full font-medium"
  190. >
  191. {{ system_info.cpu.physical_cores }} núcleos
  192. </p>
  193. </div>
  194. <div class="flex flex-col items-center justify-center">
  195. <div class="relative w-36 h-36">
  196. <svg viewBox="0 0 36 36" class="block mx-auto">
  197. <path
  198. class="fill-none stroke-blue-100 stroke-[3.5]"
  199. d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
  200. />
  201. <path
  202. id="ram-ring"
  203. class="circle-animation fill-none stroke-linecap-round stroke-blue-600 stroke-[3.5]"
  204. stroke-dasharray="0,100"
  205. d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
  206. />
  207. <text
  208. id="ram-used"
  209. x="18"
  210. y="18"
  211. class="text-[0.5rem] fill-gray-500"
  212. text-anchor="middle"
  213. dominant-baseline="middle"
  214. >
  215. 0G
  216. </text>
  217. </svg>
  218. </div>
  219. <h3 class="mt-2 font-semibold text-gray-700">RAM</h3>
  220. <p
  221. class="text-xs mt-1 bg-blue-500 text-white px-2 py-0.5 rounded-full font-medium"
  222. >
  223. {{ system_info.ram.total }}
  224. </p>
  225. </div>
  226. <div class="flex flex-col items-center justify-center">
  227. <div class="relative w-36 h-36">
  228. <svg viewBox="0 0 36 36" class="block mx-auto">
  229. <path
  230. class="fill-none stroke-emerald-100 stroke-[3.5]"
  231. d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
  232. />
  233. <path
  234. id="swap-ring"
  235. class="circle-animation fill-none stroke-linecap-round stroke-emerald-500 stroke-[3.5]"
  236. stroke-dasharray="0,100"
  237. d="M18 2.0845 a 15.9155 15.9155 0 0 1 0 31.831 a 15.9155 15.9155 0 0 1 0 -31.831"
  238. />
  239. <text
  240. id="swap-used"
  241. x="18"
  242. y="18"
  243. class="text-[0.5rem] fill-gray-500"
  244. text-anchor="middle"
  245. dominant-baseline="middle"
  246. >
  247. 0G
  248. </text>
  249. </svg>
  250. </div>
  251. <h3 class="mt-2 font-semibold text-gray-700">SWAP</h3>
  252. <p
  253. class="text-xs mt-1 bg-emerald-500 text-white px-2 py-0.5 rounded-full font-medium"
  254. >
  255. {{ system_info.swap.total }}
  256. </p>
  257. </div>
  258. </div>
  259. </div>
  260. <div class="bg-white rounded-xl shadow-lg p-6">
  261. <div class="flex items-center mb-6">
  262. <i class="fas fa-info-circle text-2xl text-blue-600 mr-3"></i>
  263. <h2 class="text-xl font-bold text-gray-800">
  264. Información del Sistema
  265. </h2>
  266. </div>
  267. <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
  268. <div class="flex items-start">
  269. <i class="fas fa-server text-gray-500 mt-1 mr-3"></i>
  270. <div>
  271. <h3 class="text-sm font-semibold text-gray-600">
  272. Nombre del Host
  273. </h3>
  274. <p id="hostname" class="text-gray-800">
  275. {{ system_info.hostname }}
  276. </p>
  277. </div>
  278. </div>
  279. <div class="flex items-start">
  280. <i class="fas fa-network-wired text-gray-500 mt-1 mr-3"></i>
  281. <div>
  282. <h3 class="text-sm font-semibold text-gray-600">
  283. Direcciones IP
  284. </h3>
  285. <p id="ip-addresses" class="text-gray-800">
  286. {% for ip in system_info.ips %}{{ ip.ip }}<br />{% endfor
  287. %}
  288. </p>
  289. </div>
  290. </div>
  291. <div class="flex items-start">
  292. <i class="fab fa-linux text-gray-500 mt-1 mr-3"></i>
  293. <div>
  294. <h3 class="text-sm font-semibold text-gray-600">
  295. Sistema Operativo
  296. </h3>
  297. <p id="os-info" class="text-gray-800">
  298. {{ system_info.os }}
  299. </p>
  300. </div>
  301. </div>
  302. <div class="flex items-start">
  303. <i class="fas fa-clock text-gray-500 mt-1 mr-3"></i>
  304. <div>
  305. <h3 class="text-sm font-semibold text-gray-600">
  306. Tiempo Encendido
  307. </h3>
  308. <p id="uptime" class="text-gray-800">
  309. {{ system_info.uptime }}
  310. </p>
  311. </div>
  312. </div>
  313. <div class="flex items-start">
  314. <i class="fas fa-globe text-gray-500 mt-1 mr-3"></i>
  315. <div>
  316. <h3 class="text-sm font-semibold text-gray-600">
  317. Zona Horaria
  318. </h3>
  319. <p id="timezone" class="text-gray-800">
  320. {{ system_info.timezone }}
  321. </p>
  322. </div>
  323. </div>
  324. <div class="flex items-start">
  325. <i class="fas fa-clock text-gray-500 mt-1 mr-3"></i>
  326. <div>
  327. <h3 class="text-sm font-semibold text-gray-600">
  328. Hora Local
  329. </h3>
  330. <p id="local-time" class="text-gray-800">
  331. {{ system_info.local_time }}
  332. </p>
  333. </div>
  334. </div>
  335. </div>
  336. </div>
  337. </div>
  338. </section>
  339. <section class="bg-white rounded-xl shadow-lg p-6 mb-12">
  340. <div class="flex items-center justify-between mb-6">
  341. <h2 class="text-xl font-bold text-gray-800">
  342. Gráficas del Sistema
  343. </h2>
  344. <div class="flex bg-gray-100 rounded-lg p-1">
  345. <button
  346. id="todayBtn"
  347. class="time-range-btn active px-4 py-2 rounded-md text-sm font-medium text-blue-600 bg-white shadow"
  348. >
  349. Hoy
  350. </button>
  351. <button
  352. id="24hoursBtn"
  353. class="time-range-btn px-4 py-2 rounded-md text-sm font-medium text-gray-500 hover:text-blue-600"
  354. >
  355. 24 Horas
  356. </button>
  357. </div>
  358. </div>
  359. <div class="flex border-b mb-6">
  360. <button
  361. class="tab-btn active py-3 px-6 font-medium border-b-2 border-blue-600 text-blue-600 transition-all duration-300 ease-in-out hover:bg-slate-100"
  362. >
  363. CPU
  364. </button>
  365. <button
  366. class="tab-btn py-3 px-6 font-medium text-gray-500 hover:text-blue-600 transition-all duration-300 ease-in-out hover:bg-slate-100"
  367. >
  368. RAM
  369. </button>
  370. <button
  371. class="tab-btn py-3 px-6 font-medium text-gray-500 hover:text-blue-600 transition-all duration-300 ease-in-out hover:bg-slate-100"
  372. >
  373. SWAP
  374. </button>
  375. </div>
  376. <div class="tab-content active">
  377. <div class="h-80"><canvas id="cpuChart"></canvas></div>
  378. </div>
  379. <div class="tab-content">
  380. <div class="h-80"><canvas id="ramChart"></canvas></div>
  381. </div>
  382. <div class="tab-content">
  383. <div class="h-80"><canvas id="swapChart"></canvas></div>
  384. </div>
  385. </section>
  386. </div>
  387. <div id="cacheContent" class="main-tab-content">
  388. <section class="cache-stats">
  389. <div class="bg-white rounded-xl shadow-lg p-6 mb-8">
  390. <div class="flex items-center mb-6">
  391. <i class="fas fa-database text-2xl text-blue-600 mr-3"></i>
  392. <h2 class="text-2xl font-bold text-gray-800">
  393. Estadísticas de Caché
  394. </h2>
  395. </div>
  396. <div
  397. class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 gap-8 max-w-[1000px] mx-auto"
  398. >
  399. {{ flip_card(icon='fas fa-database', title='Entradas almacenadas',
  400. value=cache_stats.store_entries, back_title='Entradas
  401. Almacenadas', description='Número de objetos actualmente en la
  402. caché de Squid.') }} {{ flip_card(icon='fas fa-chart-pie',
  403. title='Uso de capacidad', value=cache_stats.capacity_used,
  404. back_title='Uso de capacidad', description='Porcentaje del
  405. almacenamiento de caché en uso actualmente.') }} {% if
  406. cache_stats.fs_space_total and cache_stats.fs_space_total > 0 %}
  407. {% set total_space_html %}{% if (cache_stats.fs_space_total /
  408. 1024) < 1024 %}
  409. <p class="text-xl text-blue-800" data-stat="espacio_total">
  410. {{ (cache_stats.fs_space_total / 1024)|int }} MB
  411. </p>
  412. {% else %}
  413. <p class="text-xl text-blue-800" data-stat="espacio_total">
  414. {{ (cache_stats.fs_space_total / 1024 / 1024)|round(2) }} GB
  415. </p>
  416. {% endif %}{% endset %} {{ flip_card(icon='fas fa-hdd',
  417. title='Espacio total', back_title='Espacio total',
  418. description='Tamaño total del disco asignado a la caché de
  419. Squid.', extra_html=total_space_html) }} {% else %} {{
  420. flip_card(icon='fas fa-hdd', title='Espacio total',
  421. back_title='Espacio total', description='Tamaño total del disco
  422. asignado a la caché de Squid.', extra_html='
  423. <p class="text-xl text-red-600">No disponible</p>
  424. ') }} {% endif %} {% set used_space_html %}{% if
  425. (cache_stats.fs_space_used / 1024) < 1024 %}
  426. <p class="text-xl text-blue-800" data-stat="espacio_usado">
  427. {{ (cache_stats.fs_space_used / 1024)|int }} MB
  428. </p>
  429. {% else %}
  430. <p class="text-xl text-blue-800" data-stat="espacio_usado">
  431. {{ (cache_stats.fs_space_used / 1024 / 1024)|round(2) }} GB
  432. </p>
  433. {% endif %}{% endset %}{{ flip_card(icon='fas fa-folder-open',
  434. title='Espacio usado', back_title='Espacio usado',
  435. description='Cantidad de espacio de disco ya ocupado por objetos
  436. en caché.', extra_html=used_space_html) }} {{ flip_card(icon='fas
  437. fa-recycle', title='Eliminación',
  438. value=cache_stats.removal_policy, back_title='Política de
  439. eliminación', description='Método que Squid usa para eliminar
  440. objetos antiguos de la caché.') }} {{ flip_card(icon='fas
  441. fa-clock', title='Edad LRU', value=cache_stats.lru_age_days ~ '
  442. días', back_title='Edad LRU', description='Tiempo desde que el
  443. objeto menos usado fue accedido por última vez.') }}
  444. </div>
  445. </div>
  446. </section>
  447. </div>
  448. <div id="networkContent" class="main-tab-content">
  449. <section class="bg-white rounded-xl shadow-lg p-6">
  450. <div class="flex items-center mb-6">
  451. <i class="fas fa-network-wired text-2xl text-blue-600 mr-3"></i>
  452. <h2 class="text-xl font-bold text-gray-800">Tráfico de Red</h2>
  453. </div>
  454. <div class="h-80"><canvas id="networkChart"></canvas></div>
  455. </section>
  456. </div>
  457. </div>
  458. <script>
  459. Chart.register(ChartDataLabels);
  460. let maxRamBytes = 0,
  461. maxSwapBytes = 0;
  462. const historySize = 240; // Reducido de 720 a 240 (4 horas de datos con intervalos de 1 minuto)
  463. let liveDataCounter = 0; // Contador para manejar datos en vivo
  464. // --- FUNCIONES ORIGINALES (COMPLETAS Y RESTAURADAS) ---
  465. function getLocalTimeString() {
  466. const now = new Date();
  467. let hours = now.getHours();
  468. const minutes = now.getMinutes().toString().padStart(2, "0");
  469. const ampm = hours >= 12 ? "PM" : "AM";
  470. hours = hours % 12 || 12;
  471. return `${hours}:${minutes} ${ampm}`;
  472. }
  473. function formatTime(date) {
  474. let hours = date.getHours();
  475. const minutes = date.getMinutes().toString().padStart(2, "0");
  476. const ampm = hours >= 12 ? "PM" : "AM";
  477. hours = hours % 12 || 12;
  478. return `${hours}:${minutes} ${ampm}`;
  479. }
  480. function openMainTab(tabName) {
  481. document
  482. .querySelectorAll(".main-tab-content")
  483. .forEach((content) => content.classList.remove("active"));
  484. document.querySelectorAll(".main-tab-btn").forEach((btn) => {
  485. btn.classList.remove("active", "text-blue-600");
  486. btn.classList.add("text-gray-500");
  487. });
  488. document.getElementById(tabName + "Content").classList.add("active");
  489. const tabBtn = document.getElementById(tabName + "Tab");
  490. tabBtn.classList.add("active", "text-blue-600");
  491. tabBtn.classList.remove("text-gray-500");
  492. }
  493. document
  494. .getElementById("dashboardTab")
  495. .addEventListener("click", () => openMainTab("dashboard"));
  496. document
  497. .getElementById("cacheTab")
  498. .addEventListener("click", () => openMainTab("cache"));
  499. document
  500. .getElementById("networkTab")
  501. .addEventListener("click", () => openMainTab("network"));
  502. document.querySelectorAll(".tab-btn").forEach((button, index) => {
  503. button.addEventListener("click", () => {
  504. document.querySelectorAll(".tab-btn").forEach((btn) => {
  505. btn.classList.remove(
  506. "active",
  507. "text-blue-600",
  508. "border-b-2",
  509. "border-blue-600"
  510. );
  511. btn.classList.add("text-gray-500");
  512. });
  513. button.classList.add(
  514. "active",
  515. "text-blue-600",
  516. "border-b-2",
  517. "border-blue-600"
  518. );
  519. button.classList.remove("text-gray-500");
  520. document
  521. .querySelectorAll(".tab-content")
  522. .forEach((content) => content.classList.remove("active"));
  523. document
  524. .querySelectorAll(".tab-content")
  525. [index].classList.add("active");
  526. });
  527. });
  528. const chartOptions = {
  529. responsive: true,
  530. maintainAspectRatio: false,
  531. tension: 0.3,
  532. fill: true,
  533. pointRadius: 2,
  534. scales: {
  535. x: { grid: { color: "rgba(0, 0, 0, 0.05)" } },
  536. y: { beginAtZero: true, grid: { color: "rgba(0, 0, 0, 0.05)" } },
  537. },
  538. plugins: { legend: { display: true }, datalabels: { display: false } },
  539. };
  540. const cpuChart = new Chart("cpuChart", {
  541. type: "line",
  542. data: {
  543. labels: [],
  544. datasets: [
  545. {
  546. label: "Uso de CPU (%)",
  547. data: [],
  548. borderColor: "#ef4444",
  549. backgroundColor: "rgba(239, 68, 68, 0.1)",
  550. pointBackgroundColor: "#ef4444",
  551. },
  552. ],
  553. },
  554. options: {
  555. ...chartOptions,
  556. scales: {
  557. ...chartOptions.scales,
  558. y: {
  559. ...chartOptions.scales.y,
  560. max: 100,
  561. title: { display: true, text: "%" },
  562. },
  563. },
  564. },
  565. });
  566. const ramChart = new Chart("ramChart", {
  567. type: "line",
  568. data: {
  569. labels: [],
  570. datasets: [
  571. {
  572. label: "RAM Usada",
  573. data: [],
  574. borderColor: "#3b82f6",
  575. backgroundColor: "rgba(59, 130, 246, 0.1)",
  576. pointBackgroundColor: "#3b82f6",
  577. },
  578. ],
  579. },
  580. options: {
  581. ...chartOptions,
  582. scales: {
  583. ...chartOptions.scales,
  584. y: {
  585. ...chartOptions.scales.y,
  586. title: { display: true, text: "Bytes" },
  587. ticks: { callback: formatSizeCompact },
  588. },
  589. },
  590. plugins: {
  591. ...chartOptions.plugins,
  592. tooltip: {
  593. callbacks: {
  594. label: (ctx) => "RAM Usada: " + formatSizeCompact(ctx.raw),
  595. },
  596. },
  597. },
  598. },
  599. });
  600. const swapChart = new Chart("swapChart", {
  601. type: "line",
  602. data: {
  603. labels: [],
  604. datasets: [
  605. {
  606. label: "Swap Usada",
  607. data: [],
  608. borderColor: "#10b981",
  609. backgroundColor: "rgba(16, 185, 129, 0.1)",
  610. pointBackgroundColor: "#10b981",
  611. },
  612. ],
  613. },
  614. options: {
  615. ...chartOptions,
  616. scales: {
  617. ...chartOptions.scales,
  618. y: {
  619. ...chartOptions.scales.y,
  620. title: { display: true, text: "Bytes" },
  621. ticks: { callback: formatSizeCompact },
  622. },
  623. },
  624. plugins: {
  625. ...chartOptions.plugins,
  626. tooltip: {
  627. callbacks: {
  628. label: (ctx) => "SWAP Usada: " + formatSizeCompact(ctx.raw),
  629. },
  630. },
  631. },
  632. },
  633. });
  634. const networkChart = new Chart("networkChart", {
  635. type: "line",
  636. data: {
  637. labels: [],
  638. datasets: [
  639. {
  640. label: "Subida (Mbps)",
  641. data: [],
  642. borderColor: "#06b6d4",
  643. backgroundColor: "rgba(6,182,212,0.1)",
  644. pointBackgroundColor: "#06b6d4",
  645. },
  646. {
  647. label: "Bajada (Mbps)",
  648. data: [],
  649. borderColor: "#f59e42",
  650. backgroundColor: "rgba(245,158,66,0.1)",
  651. pointBackgroundColor: "#f59e42",
  652. },
  653. ],
  654. },
  655. options: {
  656. ...chartOptions,
  657. scales: {
  658. ...chartOptions.scales,
  659. y: {
  660. ...chartOptions.scales.y,
  661. title: { display: true, text: "Mbps" },
  662. },
  663. },
  664. },
  665. });
  666. function formatSizeCompact(bytes) {
  667. if (bytes === 0) return "0 B";
  668. const units = ["B", "KB", "MB", "GB"];
  669. const i = Math.floor(Math.log(bytes) / Math.log(1024));
  670. return `${parseFloat(
  671. (bytes / Math.pow(1024, i)).toFixed(i === 0 ? 0 : 1)
  672. )} ${units[i]}`;
  673. }
  674. function parseSize(sizeStr) {
  675. if (!sizeStr) return { value: 0, unit: "B" };
  676. const parts = sizeStr.trim().split(" ");
  677. return {
  678. value: parseFloat(parts[0]) || 0,
  679. unit: parts.length > 1 ? parts[1].charAt(0) : "B",
  680. };
  681. }
  682. function sizeToBytes(sizeStr) {
  683. const { value, unit } = parseSize(sizeStr);
  684. const multipliers = { G: 1024 * 1024 * 1024, M: 1024 * 1024, K: 1024 };
  685. return value * (multipliers[unit] || 1);
  686. }
  687. function updateRings(info) {
  688. const cpuPercent = parseFloat(info.cpu.usage.replace("%", ""));
  689. document
  690. .getElementById("cpu-ring")
  691. .setAttribute("stroke-dasharray", `${cpuPercent},100`);
  692. document.getElementById(
  693. "cpu-value"
  694. ).textContent = `${cpuPercent.toFixed(1)}%`;
  695. const ramUsedInfo = parseSize(info.ram.used);
  696. document.getElementById(
  697. "ram-used"
  698. ).textContent = `${ramUsedInfo.value.toFixed(1)}${ramUsedInfo.unit}`;
  699. document
  700. .getElementById("ram-ring")
  701. .setAttribute(
  702. "stroke-dasharray",
  703. `${parseFloat(info.ram.percent.replace("%", ""))},100`
  704. );
  705. const swapUsedInfo = parseSize(info.swap.used);
  706. document.getElementById(
  707. "swap-used"
  708. ).textContent = `${swapUsedInfo.value.toFixed(1)}${swapUsedInfo.unit}`;
  709. document
  710. .getElementById("swap-ring")
  711. .setAttribute(
  712. "stroke-dasharray",
  713. `${parseFloat(info.swap.percent.replace("%", "") || 0)},100`
  714. );
  715. }
  716. function updateSystemInfo(info) {
  717. document.getElementById("hostname").textContent = info.hostname;
  718. document.getElementById("ip-addresses").innerHTML = info.ips
  719. .map((ip) => ip.ip)
  720. .join("<br>");
  721. document.getElementById("os-info").textContent = info.os;
  722. document.getElementById("uptime").textContent = info.uptime;
  723. document.getElementById("local-time").textContent = info.local_time;
  724. }
  725. function updateCard(statId, value, isSize = false) {
  726. const element = document.querySelector(`[data-stat="${statId}"]`);
  727. if (!element) return;
  728. let formattedValue = value;
  729. if (isSize) {
  730. const bytes = parseFloat(value);
  731. formattedValue =
  732. bytes / (1024 * 1024) < 1
  733. ? `${Math.round(bytes / 1024)} MB`
  734. : `${(bytes / (1024 * 1024)).toFixed(2)} GB`;
  735. }
  736. if (element.textContent !== formattedValue.toString()) {
  737. element.textContent = formattedValue;
  738. element.classList.add("value-change");
  739. setTimeout(() => element.classList.remove("value-change"), 1000);
  740. }
  741. }
  742. function updateCacheStats(stats) {
  743. updateCard("entradas_almacenadas", stats.store_entries);
  744. updateCard("uso_de_capacidad", stats.capacity_used);
  745. updateCard("espacio_total", stats.fs_space_total, true);
  746. updateCard("espacio_usado", stats.fs_space_used, true);
  747. updateCard("eliminación", stats.removal_policy);
  748. updateCard("edad_lru", `${stats.lru_age_days} días`);
  749. }
  750. // --- AÑADIDO: Carga de datos históricos desde la API con sampling optimizado ---
  751. function loadHistoricData(endpoint = "/api/metrics/24hours") {
  752. fetch(endpoint)
  753. .then((response) => response.json())
  754. .then((data) => {
  755. if (!data || data.length === 0) {
  756. console.log(
  757. `No hay historial de métricas para el endpoint: ${endpoint}`
  758. );
  759. return;
  760. }
  761. // Implementar sampling inteligente para evitar sobrecarga
  762. let sampledData = data;
  763. if (data.length > 288) {
  764. // Si hay más de 288 puntos (4.8 horas con intervalos de 1 minuto)
  765. const sampleRate = Math.ceil(data.length / 288);
  766. sampledData = data.filter((_, index) => index % sampleRate === 0);
  767. console.log(
  768. `Aplicado sampling: ${data.length} → ${sampledData.length} puntos`
  769. );
  770. }
  771. const labels = [],
  772. cpuData = [],
  773. ramData = [],
  774. swapData = [],
  775. netUpData = [],
  776. netDownData = [];
  777. sampledData.forEach((metric) => {
  778. // Crear fecha local desde el timestamp del servidor (ya incluye timezone)
  779. const localDate = new Date(metric.timestamp);
  780. labels.push(formatTime(localDate));
  781. cpuData.push(parseFloat(metric.cpu_usage).toFixed(1));
  782. ramData.push(metric.ram_usage_bytes);
  783. swapData.push(metric.swap_usage_bytes);
  784. netUpData.push(
  785. ((metric.net_sent_bytes_sec * 8) / 1000000).toFixed(2)
  786. );
  787. netDownData.push(
  788. ((metric.net_recv_bytes_sec * 8) / 1000000).toFixed(2)
  789. );
  790. });
  791. const charts = [cpuChart, ramChart, swapChart, networkChart];
  792. const chartData = [
  793. cpuData,
  794. ramData,
  795. swapData,
  796. [netUpData, netDownData],
  797. ];
  798. charts.forEach((chart, chartIndex) => {
  799. chart.data.labels = [...labels];
  800. if (chartIndex === 3) {
  801. chart.data.datasets[0].data = chartData[chartIndex][0];
  802. chart.data.datasets[1].data = chartData[chartIndex][1];
  803. } else {
  804. chart.data.datasets[0].data = chartData[chartIndex];
  805. }
  806. chart.update();
  807. });
  808. })
  809. .catch((error) =>
  810. console.error("Error al cargar historial de métricas:", error)
  811. );
  812. }
  813. // --- AÑADIDO: Funcionalidad para alternar entre vistas de tiempo ---
  814. function setupTimeRangeButtons() {
  815. const todayBtn = document.getElementById("todayBtn");
  816. const hoursBtn = document.getElementById("24hoursBtn");
  817. todayBtn.addEventListener("click", () => {
  818. setActiveTimeRange(todayBtn, hoursBtn);
  819. loadHistoricData("/api/metrics/today");
  820. });
  821. hoursBtn.addEventListener("click", () => {
  822. setActiveTimeRange(hoursBtn, todayBtn);
  823. loadHistoricData("/api/metrics/24hours");
  824. });
  825. }
  826. function setActiveTimeRange(activeBtn, inactiveBtn) {
  827. activeBtn.classList.add("active");
  828. activeBtn.classList.remove("text-gray-500");
  829. activeBtn.classList.add("text-blue-600", "bg-white", "shadow");
  830. inactiveBtn.classList.remove("active");
  831. inactiveBtn.classList.add("text-gray-500");
  832. inactiveBtn.classList.remove("text-blue-600", "bg-white", "shadow");
  833. }
  834. const socket = io();
  835. socket.on("system_update", function (data) {
  836. updateRings(data.system_info);
  837. updateSystemInfo(data.system_info);
  838. updateCacheStats(data.cache_stats);
  839. // Incrementar contador de datos en vivo
  840. liveDataCounter++;
  841. // Solo actualizar gráficas cada 4 actualizaciones (1 minuto) para evitar sobrecarga
  842. if (liveDataCounter % 4 === 0) {
  843. // --- MODIFICADO: Lógica para añadir datos en vivo a las gráficas ---
  844. function appendLiveData(chart, label, newData) {
  845. chart.data.labels.push(label);
  846. chart.data.datasets.forEach((dataset, index) => {
  847. const dataPoint = Array.isArray(newData)
  848. ? newData[index]
  849. : newData;
  850. dataset.data.push(dataPoint);
  851. });
  852. while (chart.data.labels.length > historySize) {
  853. chart.data.labels.shift();
  854. chart.data.datasets.forEach((dataset) => dataset.data.shift());
  855. }
  856. chart.update("none");
  857. }
  858. // --- CORREGIDO: Se usa la hora local del cliente para la etiqueta en vivo ---
  859. const newLabel = getLocalTimeString();
  860. appendLiveData(
  861. cpuChart,
  862. newLabel,
  863. parseFloat(data.system_info.cpu.usage.replace("%", ""))
  864. );
  865. appendLiveData(
  866. ramChart,
  867. newLabel,
  868. sizeToBytes(data.system_info.ram.used)
  869. );
  870. appendLiveData(
  871. swapChart,
  872. newLabel,
  873. sizeToBytes(data.system_info.swap.used)
  874. );
  875. if (data.network_stats) {
  876. appendLiveData(networkChart, newLabel, [
  877. data.network_stats.up_mbps,
  878. data.network_stats.down_mbps,
  879. ]);
  880. }
  881. }
  882. });
  883. document.addEventListener("DOMContentLoaded", function () {
  884. maxRamBytes = sizeToBytes("{{ system_info.ram.total }}");
  885. maxSwapBytes = sizeToBytes("{{ system_info.swap.total }}");
  886. ramChart.options.scales.y.max = maxRamBytes;
  887. swapChart.options.scales.y.max = maxSwapBytes;
  888. updateRings({
  889. cpu: {
  890. usage: "{{ system_info.cpu.usage }}",
  891. percent: "{{ system_info.cpu.usage }}",
  892. },
  893. ram: {
  894. used: "{{ system_info.ram.used }}",
  895. percent: "{{ system_info.ram.percent }}",
  896. },
  897. swap: {
  898. used: "{{ system_info.swap.used }}",
  899. percent: "{{ system_info.swap.percent }}",
  900. },
  901. });
  902. // Inicializar botones de rango de tiempo
  903. setupTimeRangeButtons();
  904. // Cargar datos históricos (por defecto 24 horas)
  905. loadHistoricData("/api/metrics/24hours");
  906. });
  907. </script>
  908. </body>
  909. </html>