| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959 |
- 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
-
- 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);
- } 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>
- </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}`);
- }
- }
|