| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573 |
- {% extends 'layouts/base.html' %}
- {% macro flip_card(icon, title, value, back_title, description, extra_html='')%}
- <div class="group w-full h-48 [perspective:1000px]">
- <div
- class="relative h-full w-full rounded-xl shadow-xl transition-all duration-500 [transform-style:preserve-3d] group-hover:[transform:rotateY(180deg)]">
- <div
- class="absolute inset-0 bg-white shadow-md rounded-xl flex flex-col items-center justify-center [backface-visibility:hidden]">
- <i class="{{ icon }} text-3xl text-blue-600 mb-2"></i>
- <h3 class="text-lg font-semibold text-gray-800">{{ title }}</h3>
- {% if extra_html %} {{ extra_html | safe }} {% else %}
- <p class="text-xl text-blue-800" data-stat="{{ title|replace(' ', '_')|lower }}">
- {{ value }}
- </p>
- {% endif %}
- </div>
- <div class="absolute inset-0 bg-blue-600 text-white rounded-xl px-4 py-6 text-center [transform:rotateY(180deg)] [backface-visibility:hidden]">
- <h3 class="text-lg font-semibold mb-2">{{ back_title }}</h3>
- <p class="text-sm">{{ description }}</p>
- </div>
- </div>
- </div>
- {% endmacro %}
- {% block styles %}
- <script src="{{ url_for('static', filename='js/tailwindcss.js') }}"></script>
- <style>
- @keyframes progress {
- 0% {
- stroke-dasharray: 0 100;
- }
- }
- .circle-animation {
- animation: progress 1s ease-out forwards;
- }
- .main-tab-content,
- .tab-content {
- display: none;
- }
- .main-tab-content.active,
- .tab-content.active {
- display: block;
- animation: fadeIn 0.5s ease;
- }
- @keyframes fadeIn {
- from {
- opacity: 0;
- }
- to {
- opacity: 1;
- }
- }
- .main-tab-btn.active::after {
- content: "";
- position: absolute;
- bottom: 0;
- left: 0;
- right: 0;
- height: 3px;
- background-color: #3b82f6;
- animation: underline 0.3s ease;
- }
- @keyframes underline {
- from {
- transform: scaleX(0);
- }
- to {
- transform: scaleX(1);
- }
- }
- .value-change {
- animation: pulse 1s;
- }
- @keyframes pulse {
- 0% {
- transform: scale(1);
- }
- 50% {
- transform: scale(1.1);
- }
- 100% {
- transform: scale(1);
- }
- }
- .time-range-btn {
- transition: all 0.3s ease;
- }
- .time-range-btn.active {
- background-color: white;
- color: #2563eb;
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
- }
- .time-range-btn:not(.active) {
- background-color: transparent;
- color: #6b7280;
- }
- .time-range-btn:not(.active):hover {
- color: #2563eb;
- }
- </style>
- {% endblock styles %}
- {% block content %}
- {% include 'partials/cache_stats.html' %}
- {% endblock content %}
- {% block scripts %}
- <script src="{{ url_for('static', filename='js/chart.js') }}"></script>
- <script src="{{ url_for('static', filename='js/chartjs-plugin-datalabels.js') }}"></script>
- <script>
- Chart.register(ChartDataLabels);
- let maxRamBytes = 0,
- maxSwapBytes = 0;
- const historySize = 240; // Reducido de 720 a 240 (4 horas de datos con intervalos de 1 minuto)
- let liveDataCounter = 0; // Contador para manejar datos en vivo
- // --- FUNCIONES ORIGINALES (COMPLETAS Y RESTAURADAS) ---
- function getLocalTimeString() {
- const now = new Date();
- let hours = now.getHours();
- const minutes = now.getMinutes().toString().padStart(2, "0");
- const ampm = hours >= 12 ? "PM" : "AM";
- hours = hours % 12 || 12;
- return `${hours}:${minutes} ${ampm}`;
- }
- function formatTime(date) {
- let hours = date.getHours();
- const minutes = date.getMinutes().toString().padStart(2, "0");
- const ampm = hours >= 12 ? "PM" : "AM";
- hours = hours % 12 || 12;
- return `${hours}:${minutes} ${ampm}`;
- }
- function openMainTab(tabName) {
- document
- .querySelectorAll(".main-tab-content")
- .forEach((content) => content.classList.remove("active"));
- document.querySelectorAll(".main-tab-btn").forEach((btn) => {
- btn.classList.remove("active", "text-blue-600");
- btn.classList.add("text-gray-500");
- });
- document.getElementById(tabName + "Content").classList.add("active");
- const tabBtn = document.getElementById(tabName + "Tab");
- tabBtn.classList.add("active", "text-blue-600");
- tabBtn.classList.remove("text-gray-500");
- }
- document
- .getElementById("dashboardTab")
- .addEventListener("click", () => openMainTab("dashboard"));
- document
- .getElementById("cacheTab")
- .addEventListener("click", () => openMainTab("cache"));
- document
- .getElementById("networkTab")
- .addEventListener("click", () => openMainTab("network"));
- document.querySelectorAll(".tab-btn").forEach((button, index) => {
- button.addEventListener("click", () => {
- document.querySelectorAll(".tab-btn").forEach((btn) => {
- btn.classList.remove(
- "active",
- "text-blue-600",
- "border-b-2",
- "border-blue-600"
- );
- btn.classList.add("text-gray-500");
- });
- button.classList.add(
- "active",
- "text-blue-600",
- "border-b-2",
- "border-blue-600"
- );
- button.classList.remove("text-gray-500");
- document
- .querySelectorAll(".tab-content")
- .forEach((content) => content.classList.remove("active"));
- document
- .querySelectorAll(".tab-content")
- [index].classList.add("active");
- });
- });
- const chartOptions = {
- responsive: true,
- maintainAspectRatio: false,
- tension: 0.3,
- fill: true,
- pointRadius: 2,
- scales: {
- x: { grid: { color: "rgba(0, 0, 0, 0.05)" } },
- y: { beginAtZero: true, grid: { color: "rgba(0, 0, 0, 0.05)" } },
- },
- plugins: { legend: { display: true }, datalabels: { display: false } },
- };
- const cpuChart = new Chart("cpuChart", {
- type: "line",
- data: {
- labels: [],
- datasets: [
- {
- label: "Uso de CPU (%)",
- data: [],
- borderColor: "#ef4444",
- backgroundColor: "rgba(239, 68, 68, 0.1)",
- pointBackgroundColor: "#ef4444",
- },
- ],
- },
- options: {
- ...chartOptions,
- scales: {
- ...chartOptions.scales,
- y: {
- ...chartOptions.scales.y,
- max: 100,
- title: { display: true, text: "%" },
- },
- },
- },
- });
- const ramChart = new Chart("ramChart", {
- type: "line",
- data: {
- labels: [],
- datasets: [
- {
- label: "RAM Usada",
- data: [],
- borderColor: "#3b82f6",
- backgroundColor: "rgba(59, 130, 246, 0.1)",
- pointBackgroundColor: "#3b82f6",
- },
- ],
- },
- options: {
- ...chartOptions,
- scales: {
- ...chartOptions.scales,
- y: {
- ...chartOptions.scales.y,
- title: { display: true, text: "Bytes" },
- ticks: { callback: formatSizeCompact },
- },
- },
- plugins: {
- ...chartOptions.plugins,
- tooltip: {
- callbacks: {
- label: (ctx) => "RAM Usada: " + formatSizeCompact(ctx.raw),
- },
- },
- },
- },
- });
- const swapChart = new Chart("swapChart", {
- type: "line",
- data: {
- labels: [],
- datasets: [
- {
- label: {{ _('Swap Usada') | tojson }},
- data: [],
- borderColor: "#10b981",
- backgroundColor: "rgba(16, 185, 129, 0.1)",
- pointBackgroundColor: "#10b981",
- },
- ],
- },
- options: {
- ...chartOptions,
- scales: {
- ...chartOptions.scales,
- y: {
- ...chartOptions.scales.y,
- title: { display: true, text: "Bytes" },
- ticks: { callback: formatSizeCompact },
- },
- },
- plugins: {
- ...chartOptions.plugins,
- tooltip: {
- callbacks: {
- label: (ctx) => {{ _('SWAP Usada: ') | tojson }} + formatSizeCompact(ctx.raw),
- },
- },
- },
- },
- });
- const networkChart = new Chart("networkChart", {
- type: "line",
- data: {
- labels: [],
- datasets: [
- {
- label: "Subida (Mbps)",
- data: [],
- borderColor: "#06b6d4",
- backgroundColor: "rgba(6,182,212,0.1)",
- pointBackgroundColor: "#06b6d4",
- },
- {
- label: "Bajada (Mbps)",
- data: [],
- borderColor: "#f59e42",
- backgroundColor: "rgba(245,158,66,0.1)",
- pointBackgroundColor: "#f59e42",
- },
- ],
- },
- options: {
- ...chartOptions,
- scales: {
- ...chartOptions.scales,
- y: {
- ...chartOptions.scales.y,
- title: { display: true, text: "Mbps" },
- },
- },
- },
- });
- function formatSizeCompact(bytes) {
- if (bytes === 0) return "0 B";
- const units = ["B", "KB", "MB", "GB"];
- const i = Math.floor(Math.log(bytes) / Math.log(1024));
- return `${parseFloat(
- (bytes / Math.pow(1024, i)).toFixed(i === 0 ? 0 : 1)
- )} ${units[i]}`;
- }
- function parseSize(sizeStr) {
- if (!sizeStr) return { value: 0, unit: "B" };
- const parts = sizeStr.trim().split(" ");
- return {
- value: parseFloat(parts[0]) || 0,
- unit: parts.length > 1 ? parts[1].charAt(0) : "B",
- };
- }
- function sizeToBytes(sizeStr) {
- const { value, unit } = parseSize(sizeStr);
- const multipliers = { G: 1024 * 1024 * 1024, M: 1024 * 1024, K: 1024 };
- return value * (multipliers[unit] || 1);
- }
- function updateRings(info) {
- const cpuPercent = parseFloat(info.cpu.usage.replace("%", ""));
- document
- .getElementById("cpu-ring")
- .setAttribute("stroke-dasharray", `${cpuPercent},100`);
- document.getElementById(
- "cpu-value"
- ).textContent = `${cpuPercent.toFixed(1)}%`;
- const ramUsedInfo = parseSize(info.ram.used);
- document.getElementById(
- "ram-used"
- ).textContent = `${ramUsedInfo.value.toFixed(1)}${ramUsedInfo.unit}`;
- document
- .getElementById("ram-ring")
- .setAttribute(
- "stroke-dasharray",
- `${parseFloat(info.ram.percent.replace("%", ""))},100`
- );
- const swapUsedInfo = parseSize(info.swap.used);
- document.getElementById(
- "swap-used"
- ).textContent = `${swapUsedInfo.value.toFixed(1)}${swapUsedInfo.unit}`;
- document
- .getElementById("swap-ring")
- .setAttribute(
- "stroke-dasharray",
- `${parseFloat(info.swap.percent.replace("%", "") || 0)},100`
- );
- }
- function updateSystemInfo(info) {
- document.getElementById("hostname").textContent = info.hostname;
- document.getElementById("ip-addresses").innerHTML = info.ips
- .map((ip) => ip.ip)
- .join("<br>");
- document.getElementById("os-info").textContent = info.os;
- document.getElementById("uptime").textContent = info.uptime;
- document.getElementById("local-time").textContent = info.local_time;
- }
- function updateCard(statId, value, isSize = false) {
- const element = document.querySelector(`[data-stat="${statId}"]`);
- if (!element) return;
- let formattedValue = value;
- if (isSize) {
- const bytes = parseFloat(value);
- formattedValue =
- bytes / (1024 * 1024) < 1
- ? `${Math.round(bytes / 1024)} MB`
- : `${(bytes / (1024 * 1024)).toFixed(2)} GB`;
- }
- if (element.textContent !== formattedValue.toString()) {
- element.textContent = formattedValue;
- element.classList.add("value-change");
- setTimeout(() => element.classList.remove("value-change"), 1000);
- }
- }
- function updateCacheStats(stats) {
- updateCard("entradas_almacenadas", stats.store_entries);
- updateCard("uso_de_capacidad", stats.capacity_used);
- updateCard("espacio_total", stats.fs_space_total, true);
- updateCard("espacio_usado", stats.fs_space_used, true);
- updateCard("eliminación", stats.removal_policy);
- updateCard("edad_lru", `${stats.lru_age_days} días`);
- }
- // --- AÑADIDO: Carga de datos históricos desde la API con sampling optimizado ---
- function loadHistoricData(endpoint = "/api/metrics/24hours") {
- fetch(endpoint)
- .then((response) => response.json())
- .then((data) => {
- if (!data || data.length === 0) {
- return;
- }
- // Implementar sampling inteligente para evitar sobrecarga
- let sampledData = data;
- if (data.length > 288) {
- // Si hay más de 288 puntos (4.8 horas con intervalos de 1 minuto)
- const sampleRate = Math.ceil(data.length / 288);
- sampledData = data.filter((_, index) => index % sampleRate === 0);
- }
- const labels = [],
- cpuData = [],
- ramData = [],
- swapData = [],
- netUpData = [],
- netDownData = [];
- sampledData.forEach((metric) => {
- // Crear fecha local desde el timestamp del servidor (ya incluye timezone)
- const localDate = new Date(metric.timestamp);
- labels.push(formatTime(localDate));
- cpuData.push(parseFloat(metric.cpu_usage).toFixed(1));
- ramData.push(metric.ram_usage_bytes);
- swapData.push(metric.swap_usage_bytes);
- netUpData.push(
- ((metric.net_sent_bytes_sec * 8) / 1000000).toFixed(2)
- );
- netDownData.push(
- ((metric.net_recv_bytes_sec * 8) / 1000000).toFixed(2)
- );
- });
- const charts = [cpuChart, ramChart, swapChart, networkChart];
- const chartData = [
- cpuData,
- ramData,
- swapData,
- [netUpData, netDownData],
- ];
- charts.forEach((chart, chartIndex) => {
- chart.data.labels = [...labels];
- if (chartIndex === 3) {
- chart.data.datasets[0].data = chartData[chartIndex][0];
- chart.data.datasets[1].data = chartData[chartIndex][1];
- } else {
- chart.data.datasets[0].data = chartData[chartIndex];
- }
- chart.update();
- });
- })
- .catch((error) =>
- console.error("Error al cargar historial de métricas:", error)
- );
- }
- // --- AÑADIDO: Funcionalidad para alternar entre vistas de tiempo ---
- function setupTimeRangeButtons() {
- const todayBtn = document.getElementById("todayBtn");
- const hoursBtn = document.getElementById("24hoursBtn");
- todayBtn.addEventListener("click", () => {
- setActiveTimeRange(todayBtn, hoursBtn);
- loadHistoricData("/api/metrics/today");
- });
- hoursBtn.addEventListener("click", () => {
- setActiveTimeRange(hoursBtn, todayBtn);
- loadHistoricData("/api/metrics/24hours");
- });
- }
- function setActiveTimeRange(activeBtn, inactiveBtn) {
- activeBtn.classList.add("active");
- activeBtn.classList.remove("text-gray-500");
- activeBtn.classList.add("text-blue-600", "bg-white", "shadow");
- inactiveBtn.classList.remove("active");
- inactiveBtn.classList.add("text-gray-500");
- inactiveBtn.classList.remove("text-blue-600", "bg-white", "shadow");
- }
- const socket = io();
- socket.on("system_update", function (data) {
- updateRings(data.system_info);
- updateSystemInfo(data.system_info);
- updateCacheStats(data.cache_stats);
- // Incrementar contador de datos en vivo
- liveDataCounter++;
- // Solo actualizar gráficas cada 4 actualizaciones (1 minuto) para evitar sobrecarga
- if (liveDataCounter % 4 === 0) {
- // --- MODIFICADO: Lógica para añadir datos en vivo a las gráficas ---
- function appendLiveData(chart, label, newData) {
- chart.data.labels.push(label);
- chart.data.datasets.forEach((dataset, index) => {
- const dataPoint = Array.isArray(newData)
- ? newData[index]
- : newData;
- dataset.data.push(dataPoint);
- });
- while (chart.data.labels.length > historySize) {
- chart.data.labels.shift();
- chart.data.datasets.forEach((dataset) => dataset.data.shift());
- }
- chart.update("none");
- }
- // --- CORREGIDO: Se usa la hora local del cliente para la etiqueta en vivo ---
- const newLabel = getLocalTimeString();
- appendLiveData(
- cpuChart,
- newLabel,
- parseFloat(data.system_info.cpu.usage.replace("%", ""))
- );
- appendLiveData(
- ramChart,
- newLabel,
- sizeToBytes(data.system_info.ram.used)
- );
- appendLiveData(
- swapChart,
- newLabel,
- sizeToBytes(data.system_info.swap.used)
- );
- if (data.network_stats) {
- appendLiveData(networkChart, newLabel, [
- data.network_stats.up_mbps,
- data.network_stats.down_mbps,
- ]);
- }
- }
- });
- document.addEventListener("DOMContentLoaded", function () {
- maxRamBytes = sizeToBytes("{{ system_info.ram.total }}");
- maxSwapBytes = sizeToBytes("{{ system_info.swap.total }}");
- ramChart.options.scales.y.max = maxRamBytes;
- swapChart.options.scales.y.max = maxSwapBytes;
- updateRings({
- cpu: {
- usage: "{{ system_info.cpu.usage }}",
- percent: "{{ system_info.cpu.usage }}",
- },
- ram: {
- used: "{{ system_info.ram.used }}",
- percent: "{{ system_info.ram.percent }}",
- },
- swap: {
- used: "{{ system_info.swap.used }}",
- percent: "{{ system_info.swap.percent }}",
- },
- });
- // Inicializar botones de rango de tiempo
- setupTimeRangeButtons();
- // Cargar datos históricos (por defecto 24 horas)
- loadHistoricData("/api/metrics/24hours");
- });
- </script>
- {% endblock scripts %}
|