| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241 |
- const API_BASE = window.location.origin;
- let selectedVM = null;
- // Initialize dashboard
- document.addEventListener('DOMContentLoaded', () => {
- loadVMs();
- loadISOsForSelect();
-
- // Initialize sidebar state for mobile
- const sidebar = document.querySelector('.sidebar');
- if (window.innerWidth <= 768) {
- sidebar.classList.add('hidden-mobile');
- }
-
- // Create VM Form
- document.getElementById('createVMForm').addEventListener('submit', createVM);
- });
- // Get badge class based on VM state
- function getStateClass(state) {
- switch (state) {
- case 'running': return 'badge-running';
- case 'shut off': return 'badge-off';
- case 'paused': return 'badge-paused';
- case 'crashed': return 'badge-error';
- default: return 'bg-light text-dark';
- }
- }
- // Get icon for state
- function getStateIcon(state) {
- switch (state) {
- case 'running': return '<i class="bi bi-play-circle-fill"></i>';
- case 'shut off': return '<i class="bi bi-power"></i>';
- case 'paused': return '<i class="bi bi-pause-circle-fill"></i>';
- default: return '<i class="bi bi-question-circle"></i>';
- }
- }
- // Load VMs from API
- async function loadVMs() {
- try {
- const response = await fetch(`${API_BASE}/vms`);
- const data = await response.json();
- const vmList = document.getElementById('vmList');
-
- if (!data.vms || data.vms.length === 0) {
- vmList.innerHTML = '<p style="text-align: center; color: rgba(255,255,255,0.7); margin-top: 20px;">No hay máquinas virtuales</p>';
- return;
- }
-
- vmList.innerHTML = data.vms.map(vm => `
- <div class="vm-item ${selectedVM === vm.name ? 'active' : ''}" onclick="selectVM('${vm.name}')">
- <div class="vm-item-name">
- <div>${vm.name}</div>
- <small style="opacity: 0.9;">${vm.id !== -1 ? 'ID: ' + vm.id : 'Detenida'}</small>
- </div>
- <span class="vm-item-badge badge ${getStateClass(vm.state)}">${vm.state}</span>
- </div>
- `).join('');
- } catch (error) {
- console.error('Error loading VMs:', error);
- }
- }
- // Select a VM and show details
- async function selectVM(vmName) {
- selectedVM = vmName;
- loadVMs(); // Refresh to highlight selected
-
- // Clean up previous charts
- cleanupCharts();
-
- try {
- const response = await fetch(`${API_BASE}/vms/${vmName}/info`);
- const vm = await response.json();
-
- if (vm.error) {
- showError(vm.error);
- return;
- }
-
- displayVMDetails(vm, vmName);
-
- // Initialize performance charts only if VM is running
- if (vm.state === 'running') {
- setTimeout(() => initializePerformanceCharts(vmName), 100);
- }
- } catch (error) {
- console.error('Error loading VM info:', error);
- showError('Error al cargar información de la VM');
- }
- }
- // Display VM details
- function displayVMDetails(vm, vmName) {
- const contentArea = document.getElementById('contentArea');
- const topBar = document.getElementById('currentVMName');
- const topBarActions = document.getElementById('topBarActions');
-
- topBar.textContent = vmName;
-
- // Build status badge
- const statusBadge = `<span class="badge ${getStateClass(vm.state)} p-2">${vm.state}</span>`;
-
- // Build action buttons
- const actionButtons = `
- <div>
- ${vm.state === 'running' ? `
- <button class="btn btn-sm btn-warning" onclick="stopVM('${vmName}')">
- <i class="bi bi-stop-circle"></i> Detener
- </button>
- <button class="btn btn-sm btn-info" onclick="openConsole('${vmName}')">
- <i class="bi bi-display"></i> Consola
- </button>
- ` : `
- <button class="btn btn-sm btn-success" onclick="startVM('${vmName}')">
- <i class="bi bi-play-circle"></i> Iniciar
- </button>
- `}
- <button class="btn btn-sm btn-danger" onclick="deleteVMConfirm('${vmName}')">
- <i class="bi bi-trash"></i> Eliminar
- </button>
- </div>
- `;
-
- topBarActions.innerHTML = actionButtons;
-
- // Build content
- const disksHTML = vm.disks && vm.disks.length > 0 ? vm.disks.map(disk => `
- <li>
- <strong>${disk.target}</strong> (${disk.driver}) - ${disk.source}
- </li>
- `).join('') : '<li>Sin discos</li>';
-
- const interfacesHTML = vm.interfaces && vm.interfaces.length > 0 ? vm.interfaces.map(iface => `
- <li>
- <strong>MAC:</strong> ${iface.mac}<br>
- <strong>Red:</strong> ${iface.network}
- </li>
- `).join('') : '<li>Sin interfaces</li>';
-
- contentArea.innerHTML = `
- <ul class="nav nav-tabs" role="tablist">
- <li class="nav-item">
- <a class="nav-link active" id="overview-tab" data-bs-toggle="tab" href="#overview">Resumen</a>
- </li>
- <li class="nav-item">
- <a class="nav-link" id="disks-tab" data-bs-toggle="tab" href="#disks">Discos</a>
- </li>
- <li class="nav-item">
- <a class="nav-link" id="network-tab" data-bs-toggle="tab" href="#network">Red</a>
- </li>
- </ul>
-
- <div class="tab-content">
- <!-- Overview Tab -->
- <div class="tab-pane fade show active" id="overview">
- <div class="vm-details">
- <div class="card">
- <div class="card-header">
- <h6 class="card-title mb-0"><i class="bi bi-gear"></i> Configuración</h6>
- </div>
- <div class="card-body">
- <div class="info-item">
- <div class="info-label">ID de Dominio</div>
- <div class="info-value">${vm.id !== -1 ? vm.id : 'N/A (Parada)'}</div>
- </div>
- <div class="info-item">
- <div class="info-label">Estado</div>
- <div class="info-value">${statusBadge}</div>
- </div>
- <div class="info-item">
- <div class="info-label">Procesadores</div>
- <div class="info-value">${vm.cpus} CPU${vm.cpus !== 1 ? 's' : ''}</div>
- </div>
- <div class="info-item">
- <div class="info-label">Memoria RAM</div>
- <div class="info-value">${vm.memory} MiB</div>
- </div>
- </div>
- </div>
-
- <div class="card">
- <div class="card-header">
- <h6 class="card-title mb-0"><i class="bi bi-display"></i> Display</h6>
- </div>
- <div class="card-body">
- <div class="info-item">
- <div class="info-label">Puerto VNC</div>
- <div class="info-value">${vm.vnc_port ? vm.vnc_port : 'No asignado'}</div>
- </div>
- <div class="info-item">
- <div class="info-label">Dirección</div>
- <div class="info-value">${vm.vnc_port ? `localhost:${vm.vnc_port}` : 'N/A'}</div>
- </div>
- </div>
- </div>
- <!-- Performance Charts -->
- ${vm.state === 'running' ? `
- <div class="card">
- <div class="card-header">
- <h6 class="card-title mb-0"><i class="bi bi-graph-up"></i> Rendimiento</h6>
- </div>
- <div class="card-body">
- <div class="row">
- <div class="col-md-6">
- <div style="position: relative; height: 250px;">
- <canvas id="cpuChart"></canvas>
- </div>
- </div>
- <div class="col-md-6">
- <div style="position: relative; height: 250px;">
- <canvas id="memoryChart"></canvas>
- </div>
- </div>
- </div>
- </div>
- </div>
- ` : ''}
- </div>
-
- <div class="actions-group">
- <h5><i class="bi bi-lightning"></i> Acciones</h5>
- <button class="btn btn-sm btn-primary btn-action" onclick="openBootOrderModal('${vmName}')">
- <i class="bi bi-arrow-repeat"></i> Configurar Arranque
- </button>
- <button class="btn btn-sm btn-info btn-action" onclick="openAddDiskModal('${vmName}')" ${vm.state !== 'shut off' ? 'disabled' : ''}>
- <i class="bi bi-plus-circle"></i> Agregar Disco
- </button>
- <button class="btn btn-sm btn-warning btn-action" onclick="openSnapshotModal('${vmName}')">
- <i class="bi bi-camera"></i> Crear Snapshot
- </button>
- <button class="btn btn-sm btn-secondary btn-action" onclick="openSnapshotsListModal('${vmName}')">
- <i class="bi bi-collection"></i> Ver Snapshots
- </button>
- <button class="btn btn-sm btn-secondary btn-action" onclick="downloadVMConfig('${vmName}')">
- <i class="bi bi-download"></i> Descargar XML
- </button>
- </div>
- </div>
-
- <!-- Disks Tab -->
- <div class="tab-pane fade" id="disks">
- <div class="card">
- <div class="card-header">
- <h6 class="card-title mb-0"><i class="bi bi-hdd"></i> Discos</h6>
- </div>
- <div class="card-body">
- <ul class="list-unstyled">
- ${disksHTML}
- </ul>
- </div>
- </div>
- </div>
-
- <!-- Network Tab -->
- <div class="tab-pane fade" id="network">
- <div class="card">
- <div class="card-header">
- <h6 class="card-title mb-0"><i class="bi bi-diagram-3"></i> Interfaces de Red</h6>
- </div>
- <div class="card-body">
- <ul class="list-unstyled">
- ${interfacesHTML}
- </ul>
- </div>
- </div>
- </div>
- </div>
- `;
- }
- // Show error message
- function showError(message) {
- const contentArea = document.getElementById('contentArea');
- contentArea.innerHTML = `
- <div class="alert alert-danger" role="alert">
- <i class="bi bi-exclamation-circle"></i> ${message}
- </div>
- `;
- }
- // Open Create VM Modal
- function openCreateVMModal() {
- const modal = new bootstrap.Modal(document.getElementById('createVMModal'));
- modal.show();
- }
- // Create VM
- async function createVM(e) {
- e.preventDefault();
-
- const name = document.getElementById('name').value;
- const memory = document.getElementById('memory').value;
- const disk_size = document.getElementById('disk_size').value;
- const cpus = document.getElementById('cpus').value;
- const iso = document.getElementById('iso').value;
-
- if (!iso) {
- alert('Por favor selecciona una ISO');
- return;
- }
-
- try {
- const response = await fetch(`${API_BASE}/vms?name=${name}&memory=${memory}&disk_size=${disk_size}&cpus=${cpus}&iso=${iso}`, {
- method: 'POST'
- });
-
- let result;
- try {
- result = await response.json();
- } catch {
- result = { error: `Server error: ${response.status}` };
- }
-
- if (response.ok) {
- alert(result.message || 'VM creada correctamente');
- document.getElementById('createVMForm').reset();
- bootstrap.Modal.getInstance(document.getElementById('createVMModal')).hide();
- loadVMs();
- } else {
- alert(result.error || 'Error al crear VM');
- }
- } catch (error) {
- console.error('Error:', error);
- alert(`Error: ${error.message}`);
- }
- }
- // Load ISOs for select
- async function loadISOsForSelect() {
- try {
- const response = await fetch(`${API_BASE}/isos`);
- const data = await response.json();
- const select = document.getElementById('iso');
-
- select.innerHTML = '<option value="">Selecciona una ISO</option>';
- if (data.isos && data.isos.length > 0) {
- data.isos.forEach(iso => {
- select.innerHTML += `<option value="${iso.path}">${iso.name}</option>`;
- });
- }
- } catch (error) {
- console.error('Error loading ISOs:', error);
- }
- }
- // Start VM
- async function startVM(vmName) {
- try {
- const response = await fetch(`${API_BASE}/vms/${vmName}/start`);
- const result = await response.json();
-
- if (response.ok) {
- loadVMs();
- if (selectedVM === vmName) {
- selectVM(vmName);
- }
- } else {
- alert(result.error || 'Error al iniciar VM');
- }
- } catch (error) {
- console.error('Error:', error);
- alert(`Error: ${error.message}`);
- }
- }
- // Stop VM
- async function stopVM(vmName) {
- if (confirm(`¿Estás seguro de que quieres detener ${vmName}?`)) {
- try {
- const response = await fetch(`${API_BASE}/vms/${vmName}/stop`);
- const result = await response.json();
-
- if (response.ok) {
- loadVMs();
- if (selectedVM === vmName) {
- selectVM(vmName);
- }
- } else {
- alert(result.error || 'Error al detener VM');
- }
- } catch (error) {
- console.error('Error:', error);
- alert(`Error: ${error.message}`);
- }
- }
- }
- // Delete VM
- async function deleteVMConfirm(vmName) {
- if (confirm(`¿Estás seguro de que quieres eliminar ${vmName}? Esta acción no se puede deshacer.`)) {
- try {
- const response = await fetch(`${API_BASE}/vms/${vmName}`, { method: 'DELETE' });
- const result = await response.json();
-
- if (response.ok) {
- alert('VM eliminada correctamente');
- selectedVM = null;
- loadVMs();
- document.getElementById('contentArea').innerHTML = `
- <div class="empty-state">
- <i class="bi bi-inbox"></i>
- <h5>Selecciona una máquina virtual</h5>
- <p>Haz clic en una VM del panel lateral para ver sus detalles</p>
- </div>
- `;
- } else {
- alert(result.error || 'Error al eliminar VM');
- }
- } catch (error) {
- console.error('Error:', error);
- alert(`Error: ${error.message}`);
- }
- }
- }
- // Open Boot Order Modal
- function openBootOrderModal(vmName) {
- const html = `
- <div class="modal fade" id="bootOrderModal" tabindex="-1">
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <h5 class="modal-title">Configurar Orden de Arranque - ${vmName}</h5>
- <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
- </div>
- <form id="bootOrderForm">
- <div class="modal-body">
- <div class="mb-3">
- <label for="bootOrderInput" class="form-label">Orden de Arranque</label>
- <input type="text" class="form-control" id="bootOrderInput" placeholder="hd,cdrom" required>
- <small class="form-text text-muted">Separados por comas: hd, cdrom, network</small>
- </div>
- </div>
- <div class="modal-footer">
- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
- <button type="submit" class="btn btn-primary">Guardar</button>
- </div>
- </form>
- </div>
- </div>
- </div>
- `;
-
- document.body.insertAdjacentHTML('beforeend', html);
- const modal = new bootstrap.Modal(document.getElementById('bootOrderModal'));
-
- document.getElementById('bootOrderForm').addEventListener('submit', async (e) => {
- e.preventDefault();
- const order = document.getElementById('bootOrderInput').value.split(',').map(s => s.trim());
-
- try {
- const response = await fetch(`${API_BASE}/vms/${vmName}/boot-order`, {
- method: 'PUT',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ order })
- });
-
- const result = await response.json();
- if (response.ok) {
- alert('Orden de arranque actualizado');
- modal.hide();
- document.getElementById('bootOrderModal').remove();
- } else {
- alert(result.error || 'Error al actualizar');
- }
- } catch (error) {
- alert(`Error: ${error.message}`);
- }
- });
-
- modal.show();
- }
- // Open Add Disk Modal
- function openAddDiskModal(vmName) {
- const html = `
- <div class="modal fade" id="addDiskModal" tabindex="-1">
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <h5 class="modal-title">Agregar Disco - ${vmName}</h5>
- <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
- </div>
- <div class="alert alert-warning m-3">
- <small><strong>⚠️ Importante:</strong> La VM debe estar parada y el nombre del disco no debe existir</small>
- </div>
- <form id="addDiskFormModal">
- <div class="modal-body">
- <div class="mb-3">
- <label for="diskNameInput" class="form-label">Nombre del Disco</label>
- <input type="text" class="form-control" id="diskNameInput" placeholder="datos" required>
- </div>
- <div class="mb-3">
- <label for="diskSizeInput" class="form-label">Tamaño (GB)</label>
- <input type="number" class="form-control" id="diskSizeInput" value="10" min="1" required>
- </div>
- </div>
- <div class="modal-footer">
- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
- <button type="submit" class="btn btn-primary">Agregar</button>
- </div>
- </form>
- </div>
- </div>
- </div>
- `;
-
- document.body.insertAdjacentHTML('beforeend', html);
- const modal = new bootstrap.Modal(document.getElementById('addDiskModal'));
-
- document.getElementById('addDiskFormModal').addEventListener('submit', async (e) => {
- e.preventDefault();
- const disk_name = document.getElementById('diskNameInput').value;
- const disk_size = document.getElementById('diskSizeInput').value;
-
- try {
- const response = await fetch(`${API_BASE}/vms/${vmName}/add-disk?disk_name=${disk_name}&disk_size=${disk_size}`, {
- method: 'POST'
- });
-
- let result;
- try {
- result = await response.json();
- } catch {
- result = { error: 'Error del servidor' };
- }
-
- if (response.ok) {
- alert(result.message || 'Disco agregado correctamente');
- modal.hide();
- document.getElementById('addDiskModal').remove();
- selectVM(vmName); // Refresh
- } else {
- alert(result.error || 'Error al agregar disco');
- }
- } catch (error) {
- alert(`Error: ${error.message}`);
- }
- });
-
- modal.show();
- }
- // Open Console
- function openConsole(vmName) {
- fetch(`${API_BASE}/console/${vmName}`)
- .then(response => response.json())
- .then(data => {
- if (data.url) {
- window.open(data.url);
- } else {
- alert(data.error || 'Error al abrir consola');
- }
- })
- .catch(error => {
- console.error('Error:', error);
- alert('Error al abrir consola');
- });
- }
- // Open ISO Management Modal
- function openISOManagementModal() {
- const modal = new bootstrap.Modal(document.getElementById('isoManagementModal'));
- loadISOs();
- setupUploadISOForm();
- modal.show();
- }
- // Load ISOs for management
- async function loadISOs() {
- try {
- const response = await fetch(`${API_BASE}/isos`);
- const data = await response.json();
- const tbody = document.getElementById('isoTableBody');
-
- if (!data.isos || data.isos.length === 0) {
- tbody.innerHTML = '<tr><td colspan="2" class="text-center text-muted">No hay ISOs subidas</td></tr>';
- return;
- }
-
- tbody.innerHTML = data.isos.map(iso => `
- <tr>
- <td>
- <i class="bi bi-disc"></i> ${iso.name}
- </td>
- <td>
- <button class="btn btn-sm btn-danger" onclick="deleteISO('${iso.name}')">
- <i class="bi bi-trash"></i> Eliminar
- </button>
- </td>
- </tr>
- `).join('');
- } catch (error) {
- console.error('Error loading ISOs:', error);
- document.getElementById('isoTableBody').innerHTML = '<tr><td colspan="2" class="text-center text-danger">Error al cargar ISOs</td></tr>';
- }
- }
- // Setup ISO upload form
- function setupUploadISOForm() {
- const form = document.getElementById('uploadIsoForm');
- if (!form.dataset.listenerAdded) {
- form.addEventListener('submit', uploadISO);
- form.dataset.listenerAdded = 'true';
- }
- }
- // Upload ISO
- async function uploadISO(e) {
- e.preventDefault();
-
- const isoFile = document.getElementById('isoFile');
- const uploadBtn = document.getElementById('uploadBtn');
- const progressContainer = document.getElementById('progressContainer');
- const uploadProgress = document.getElementById('uploadProgress');
-
- if (!isoFile.files.length) {
- alert('Por favor selecciona un archivo');
- return;
- }
-
- const formData = new FormData();
- formData.append('file', isoFile.files[0]);
-
- uploadBtn.disabled = true;
- progressContainer.style.display = 'block';
-
- try {
- const xhr = new XMLHttpRequest();
-
- xhr.upload.addEventListener('progress', (e) => {
- if (e.lengthComputable) {
- const percentComplete = (e.loaded / e.total) * 100;
- uploadProgress.style.width = percentComplete + '%';
- uploadProgress.setAttribute('aria-valuenow', percentComplete);
- uploadProgress.textContent = Math.round(percentComplete) + '%';
- }
- });
-
- xhr.addEventListener('load', () => {
- if (xhr.status === 200) {
- const result = JSON.parse(xhr.responseText);
- alert(result.message || 'ISO subida correctamente');
- document.getElementById('uploadIsoForm').reset();
- progressContainer.style.display = 'none';
- uploadProgress.style.width = '0%';
- uploadProgress.textContent = '0%';
- loadISOs();
- loadISOsForSelect();
- } else {
- const result = JSON.parse(xhr.responseText);
- alert(result.error || 'Error al subir ISO');
- progressContainer.style.display = 'none';
- }
- uploadBtn.disabled = false;
- });
-
- xhr.addEventListener('error', () => {
- alert('Error al subir ISO');
- progressContainer.style.display = 'none';
- uploadBtn.disabled = false;
- });
-
- xhr.open('POST', `${API_BASE}/upload-iso`);
- xhr.send(formData);
- } catch (error) {
- console.error('Error:', error);
- alert(`Error: ${error.message}`);
- uploadBtn.disabled = false;
- progressContainer.style.display = 'none';
- }
- }
- // Delete ISO
- async function deleteISO(name) {
- if (confirm(`¿Estás seguro de que quieres eliminar ${name}?`)) {
- try {
- const response = await fetch(`${API_BASE}/isos/${name}`, { method: 'DELETE' });
- const result = await response.json();
-
- if (response.ok) {
- alert('ISO eliminada correctamente');
- loadISOs();
- loadISOsForSelect();
- } else {
- alert(result.error || 'Error al eliminar ISO');
- }
- } catch (error) {
- console.error('Error:', error);
- alert(`Error: ${error.message}`);
- }
- }
- }
- // Mobile responsive - Toggle sidebar
- function toggleSidebar() {
- const sidebar = document.querySelector('.sidebar');
-
- // Para móviles (max-width 768px), mostrar/ocultar el sidebar
- if (window.innerWidth <= 768) {
- sidebar.classList.toggle('show');
- }
- }
- // Cerrar sidebar cuando se selecciona una VM en móvil
- const originalSelectVM = window.selectVM;
- window.selectVM = function(vmName) {
- originalSelectVM(vmName);
-
- // Cerrar sidebar en móvil después de seleccionar
- if (window.innerWidth <= 768) {
- const sidebar = document.querySelector('.sidebar');
- sidebar.classList.remove('show');
- }
- };
- // Cerrar sidebar cuando se abre un modal
- document.addEventListener('shown.bs.modal', function() {
- if (window.innerWidth <= 768) {
- const sidebar = document.querySelector('.sidebar');
- sidebar.classList.remove('show');
- }
- });
- // Download VM configuration as XML
- async function downloadVMConfig(vmName) {
- try {
- const response = await fetch(`${API_BASE}/vms/${vmName}/config`);
-
- if (!response.ok) {
- alert(`Error: El servidor respondió con estado ${response.status}`);
- return;
- }
-
- const data = await response.json();
-
- if (data.error) {
- alert(`Error: ${data.error}`);
- return;
- }
-
- // Validar que tenemos el contenido XML
- if (!data.xml || data.xml === undefined || data.xml === 'undefined') {
- console.error('XML content is undefined or missing:', data);
- alert('Error: No se pudo obtener la configuración XML');
- return;
- }
-
- // Create a blob with the XML content
- const blob = new Blob([data.xml], { type: 'application/xml' });
- const url = window.URL.createObjectURL(blob);
- const link = document.createElement('a');
- link.href = url;
- link.download = `${vmName}-config.xml`;
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- window.URL.revokeObjectURL(url);
- } catch (error) {
- console.error('Error downloading config:', error);
- alert(`Error al descargar configuración: ${error.message}`);
- }
- }
- // Open snapshot modal
- function openSnapshotModal(vmName) {
- const modal = document.createElement('div');
- modal.classList.add('modal', 'fade');
- modal.innerHTML = `
- <div class="modal-dialog">
- <div class="modal-content">
- <div class="modal-header">
- <h5 class="modal-title">Crear Snapshot - ${vmName}</h5>
- <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
- </div>
- <div class="modal-body">
- <div class="mb-3">
- <label for="snapshotName" class="form-label">Nombre del Snapshot</label>
- <input type="text" class="form-control" id="snapshotName" placeholder="ej: snapshot-2026-01-18" required>
- </div>
- <div class="mb-3">
- <label for="snapshotDesc" class="form-label">Descripción (opcional)</label>
- <textarea class="form-control" id="snapshotDesc" rows="3" placeholder="Describe el propósito de este snapshot"></textarea>
- </div>
- </div>
- <div class="modal-footer">
- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
- <button type="button" class="btn btn-warning" onclick="createSnapshot('${vmName}')">
- <i class="bi bi-camera"></i> Crear Snapshot
- </button>
- </div>
- </div>
- </div>
- `;
-
- document.body.appendChild(modal);
- const bsModal = new bootstrap.Modal(modal);
- bsModal.show();
-
- // Limpiar modal al cerrarlo
- modal.addEventListener('hidden.bs.modal', () => {
- modal.remove();
- });
- }
- // Create snapshot
- async function createSnapshot(vmName) {
- const snapshotName = document.getElementById('snapshotName').value.trim();
- const snapshotDesc = document.getElementById('snapshotDesc').value.trim();
-
- if (!snapshotName) {
- alert('El nombre del snapshot es obligatorio');
- return;
- }
-
- // Validar que el nombre sea válido (sin espacios ni caracteres especiales)
- if (!/^[a-zA-Z0-9._-]+$/.test(snapshotName)) {
- alert('El nombre del snapshot solo puede contener letras, números, puntos, guiones y guiones bajos');
- return;
- }
-
- try {
- const url = new URL(`${API_BASE}/vms/${vmName}/snapshot`);
- url.searchParams.append('snapshot_name', snapshotName);
- if (snapshotDesc) {
- url.searchParams.append('description', snapshotDesc);
- }
-
- const response = await fetch(url, { method: 'POST' });
- const data = await response.json();
-
- if (data.error) {
- alert(`Error: ${data.error}`);
- return;
- }
-
- alert(`✓ Snapshot "${snapshotName}" creado exitosamente`);
-
- // Cerrar modal - buscar el modal visible
- const visibleModal = document.querySelector('.modal.show');
- if (visibleModal) {
- const modalInstance = bootstrap.Modal.getInstance(visibleModal);
- if (modalInstance) {
- modalInstance.hide();
- }
- }
-
- } catch (error) {
- console.error('Error:', error);
- alert(`Error al crear snapshot: ${error.message}`);
- }
- }
- // Open snapshots list modal
- function openSnapshotsListModal(vmName) {
- const modal = document.createElement('div');
- modal.classList.add('modal', 'fade');
- modal.innerHTML = `
- <div class="modal-dialog modal-lg">
- <div class="modal-content">
- <div class="modal-header">
- <h5 class="modal-title">Snapshots - ${vmName}</h5>
- <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
- </div>
- <div class="modal-body">
- <div id="snapshotsList" class="text-center">
- <p class="text-muted">Cargando snapshots...</p>
- </div>
- </div>
- <div class="modal-footer">
- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
- </div>
- </div>
- </div>
- `;
-
- document.body.appendChild(modal);
- const bsModal = new bootstrap.Modal(modal);
- bsModal.show();
-
- // Limpiar modal al cerrarlo
- modal.addEventListener('hidden.bs.modal', () => {
- modal.remove();
- });
-
- // Cargar snapshots
- loadSnapshotsList(vmName);
- }
- // Load and display snapshots list
- async function loadSnapshotsList(vmName) {
- try {
- const response = await fetch(`${API_BASE}/vms/${vmName}/snapshots`);
- const data = await response.json();
-
- if (data.error) {
- document.getElementById('snapshotsList').innerHTML = `<p class="text-danger">Error: ${data.error}</p>`;
- return;
- }
-
- const snapshots = data.snapshots;
-
- if (!snapshots || snapshots.length === 0) {
- document.getElementById('snapshotsList').innerHTML = '<p class="text-muted">No hay snapshots disponibles</p>';
- return;
- }
-
- let html = `
- <div class="table-responsive">
- <table class="table table-sm table-hover">
- <thead>
- <tr>
- <th>Nombre</th>
- <th>Creado</th>
- <th>Descripción</th>
- <th>Estado</th>
- <th>Acciones</th>
- </tr>
- </thead>
- <tbody>
- `;
-
- snapshots.forEach(snap => {
- let created = 'Desconocida';
- if (snap.created && snap.created > 0) {
- created = new Date(snap.created * 1000).toLocaleString('es-ES');
- }
- html += `
- <tr>
- <td><strong>${snap.name}</strong></td>
- <td>${created}</td>
- <td>${snap.description || '-'}</td>
- <td><span class="badge bg-info">${snap.state}</span></td>
- <td>
- <button class="btn btn-sm btn-danger" onclick="deleteSnapshotConfirm('${vmName}', '${snap.name}')">
- <i class="bi bi-trash"></i> Eliminar
- </button>
- </td>
- </tr>
- `;
- });
-
- html += `
- </tbody>
- </table>
- </div>
- `;
-
- document.getElementById('snapshotsList').innerHTML = html;
- } catch (error) {
- console.error('Error:', error);
- document.getElementById('snapshotsList').innerHTML = `<p class="text-danger">Error: ${error.message}</p>`;
- }
- }
- // Delete snapshot with confirmation
- function deleteSnapshotConfirm(vmName, snapshotName) {
- if (confirm(`¿Estás seguro de que deseas eliminar el snapshot "${snapshotName}"?`)) {
- deleteSnapshot(vmName, snapshotName);
- }
- }
- // Delete snapshot
- async function deleteSnapshot(vmName, snapshotName) {
- try {
- const encodedSnapshotName = encodeURIComponent(snapshotName);
- const response = await fetch(`${API_BASE}/vms/${vmName}/snapshots/${encodedSnapshotName}`, {
- method: 'DELETE'
- });
- const data = await response.json();
-
- if (data.error) {
- alert(`Error: ${data.error}`);
- return;
- }
-
- alert(`✓ Snapshot "${snapshotName}" eliminado exitosamente`);
-
- // Recargar lista de snapshots
- loadSnapshotsList(vmName);
- } catch (error) {
- console.error('Error:', error);
- alert(`Error al eliminar snapshot: ${error.message}`);
- }
- }
- // Chart instances storage
- let cpuChart = null;
- let memoryChart = null;
- let statsInterval = null;
- const statsHistory = {
- cpu: [],
- memory: [],
- maxPoints: 20
- };
- // Initialize and update performance charts
- async function initializePerformanceCharts(vmName) {
- // Clear any existing interval
- if (statsInterval) clearInterval(statsInterval);
-
- // Initialize charts immediately
- await updatePerformanceStats(vmName);
-
- // Update every 2 seconds
- statsInterval = setInterval(() => updatePerformanceStats(vmName), 2000);
- }
- // Update performance statistics
- async function updatePerformanceStats(vmName) {
- try {
- const response = await fetch(`${API_BASE}/vms/${vmName}/stats`);
- const data = await response.json();
-
- if (data.error || data.state === 'error') {
- console.log('VM not running or stats not available');
- return;
- }
-
- const timestamp = new Date().toLocaleTimeString('es-ES', {
- hour: '2-digit',
- minute: '2-digit',
- second: '2-digit'
- });
-
- // Update history
- statsHistory.cpu.push({
- time: timestamp,
- value: data.cpu_percent
- });
- statsHistory.memory.push({
- time: timestamp,
- value: data.memory_percent
- });
-
- // Keep only last maxPoints
- if (statsHistory.cpu.length > statsHistory.maxPoints) {
- statsHistory.cpu.shift();
- statsHistory.memory.shift();
- }
-
- // Update CPU Chart
- if (cpuChart) {
- cpuChart.data.labels = statsHistory.cpu.map(s => s.time);
- cpuChart.data.datasets[0].data = statsHistory.cpu.map(s => s.value);
- cpuChart.update('none');
- } else {
- createCPUChart();
- }
-
- // Update Memory Chart
- if (memoryChart) {
- memoryChart.data.labels = statsHistory.memory.map(s => s.time);
- memoryChart.data.datasets[0].data = statsHistory.memory.map(s => s.value);
- memoryChart.update('none');
- } else {
- createMemoryChart();
- }
-
- } catch (error) {
- console.error('Error updating stats:', error);
- }
- }
- // Create CPU chart
- function createCPUChart() {
- const ctx = document.getElementById('cpuChart');
- if (!ctx) return;
-
- // Destroy existing chart if any
- if (cpuChart) cpuChart.destroy();
-
- cpuChart = new Chart(ctx, {
- type: 'line',
- data: {
- labels: statsHistory.cpu.map(s => s.time),
- datasets: [{
- label: 'CPU (%)',
- data: statsHistory.cpu.map(s => s.value),
- borderColor: '#667eea',
- backgroundColor: 'rgba(102, 126, 234, 0.1)',
- tension: 0.4,
- fill: true,
- borderWidth: 2,
- pointRadius: 4,
- pointBackgroundColor: '#667eea',
- pointBorderColor: '#fff',
- pointBorderWidth: 2,
- pointHoverRadius: 6
- }],
- },
- options: {
- responsive: true,
- maintainAspectRatio: false,
- plugins: {
- legend: {
- display: true,
- labels: {
- font: { size: 12 },
- padding: 15,
- color: '#666'
- }
- },
- tooltip: {
- backgroundColor: 'rgba(0,0,0,0.8)',
- padding: 12,
- titleFont: { size: 12 },
- bodyFont: { size: 12 },
- callbacks: {
- label: function(context) {
- return context.dataset.label + ': ' + context.parsed.y.toFixed(2) + '%';
- }
- }
- }
- },
- scales: {
- y: {
- beginAtZero: true,
- max: 100,
- ticks: {
- stepSize: 25,
- callback: function(value) {
- return value + '%';
- }
- },
- grid: {
- color: 'rgba(0,0,0,0.05)'
- }
- },
- x: {
- grid: {
- color: 'rgba(0,0,0,0.05)'
- }
- }
- }
- }
- });
- }
- // Create Memory chart
- function createMemoryChart() {
- const ctx = document.getElementById('memoryChart');
- if (!ctx) return;
-
- // Destroy existing chart if any
- if (memoryChart) memoryChart.destroy();
-
- memoryChart = new Chart(ctx, {
- type: 'line',
- data: {
- labels: statsHistory.memory.map(s => s.time),
- datasets: [{
- label: 'Memoria (%)',
- data: statsHistory.memory.map(s => s.value),
- borderColor: '#764ba2',
- backgroundColor: 'rgba(118, 75, 162, 0.1)',
- tension: 0.4,
- fill: true,
- borderWidth: 2,
- pointRadius: 4,
- pointBackgroundColor: '#764ba2',
- pointBorderColor: '#fff',
- pointBorderWidth: 2,
- pointHoverRadius: 6
- }],
- },
- options: {
- responsive: true,
- maintainAspectRatio: false,
- plugins: {
- legend: {
- display: true,
- labels: {
- font: { size: 12 },
- padding: 15,
- color: '#666'
- }
- },
- tooltip: {
- backgroundColor: 'rgba(0,0,0,0.8)',
- padding: 12,
- titleFont: { size: 12 },
- bodyFont: { size: 12 },
- callbacks: {
- label: function(context) {
- return context.dataset.label + ': ' + context.parsed.y.toFixed(2) + '%';
- }
- }
- }
- },
- scales: {
- y: {
- beginAtZero: true,
- max: 100,
- ticks: {
- stepSize: 25,
- callback: function(value) {
- return value + '%';
- }
- },
- grid: {
- color: 'rgba(0,0,0,0.05)'
- }
- },
- x: {
- grid: {
- color: 'rgba(0,0,0,0.05)'
- }
- }
- }
- }
- });
- }
- // Clean up charts when switching VMs
- function cleanupCharts() {
- if (statsInterval) {
- clearInterval(statsInterval);
- statsInterval = null;
- }
-
- if (cpuChart) {
- cpuChart.destroy();
- cpuChart = null;
- }
-
- if (memoryChart) {
- memoryChart.destroy();
- memoryChart = null;
- }
-
- // Reset history
- statsHistory.cpu = [];
- statsHistory.memory = [];
- }
|