dashboard.js 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. const API_BASE = window.location.origin;
  2. let selectedVM = null;
  3. // Initialize dashboard
  4. document.addEventListener('DOMContentLoaded', () => {
  5. loadVMs();
  6. loadISOsForSelect();
  7. // Initialize sidebar state for mobile
  8. const sidebar = document.querySelector('.sidebar');
  9. if (window.innerWidth <= 768) {
  10. sidebar.classList.add('hidden-mobile');
  11. }
  12. // Create VM Form
  13. document.getElementById('createVMForm').addEventListener('submit', createVM);
  14. });
  15. // Get badge class based on VM state
  16. function getStateClass(state) {
  17. switch (state) {
  18. case 'running': return 'badge-running';
  19. case 'shut off': return 'badge-off';
  20. case 'paused': return 'badge-paused';
  21. case 'crashed': return 'badge-error';
  22. default: return 'bg-light text-dark';
  23. }
  24. }
  25. // Get icon for state
  26. function getStateIcon(state) {
  27. switch (state) {
  28. case 'running': return '<i class="bi bi-play-circle-fill"></i>';
  29. case 'shut off': return '<i class="bi bi-power"></i>';
  30. case 'paused': return '<i class="bi bi-pause-circle-fill"></i>';
  31. default: return '<i class="bi bi-question-circle"></i>';
  32. }
  33. }
  34. // Load VMs from API
  35. async function loadVMs() {
  36. try {
  37. const response = await fetch(`${API_BASE}/vms`);
  38. const data = await response.json();
  39. const vmList = document.getElementById('vmList');
  40. if (!data.vms || data.vms.length === 0) {
  41. vmList.innerHTML = '<p style="text-align: center; color: rgba(255,255,255,0.7); margin-top: 20px;">No hay máquinas virtuales</p>';
  42. return;
  43. }
  44. vmList.innerHTML = data.vms.map(vm => `
  45. <div class="vm-item ${selectedVM === vm.name ? 'active' : ''}" onclick="selectVM('${vm.name}')">
  46. <div class="vm-item-name">
  47. <div>${vm.name}</div>
  48. <small style="opacity: 0.9;">${vm.id !== -1 ? 'ID: ' + vm.id : 'Detenida'}</small>
  49. </div>
  50. <span class="vm-item-badge badge ${getStateClass(vm.state)}">${vm.state}</span>
  51. </div>
  52. `).join('');
  53. } catch (error) {
  54. console.error('Error loading VMs:', error);
  55. }
  56. }
  57. // Select a VM and show details
  58. async function selectVM(vmName) {
  59. selectedVM = vmName;
  60. loadVMs(); // Refresh to highlight selected
  61. try {
  62. const response = await fetch(`${API_BASE}/vms/${vmName}/info`);
  63. const vm = await response.json();
  64. if (vm.error) {
  65. showError(vm.error);
  66. return;
  67. }
  68. displayVMDetails(vm, vmName);
  69. } catch (error) {
  70. console.error('Error loading VM info:', error);
  71. showError('Error al cargar información de la VM');
  72. }
  73. }
  74. // Display VM details
  75. function displayVMDetails(vm, vmName) {
  76. const contentArea = document.getElementById('contentArea');
  77. const topBar = document.getElementById('currentVMName');
  78. const topBarActions = document.getElementById('topBarActions');
  79. topBar.textContent = vmName;
  80. // Build status badge
  81. const statusBadge = `<span class="badge ${getStateClass(vm.state)} p-2">${vm.state}</span>`;
  82. // Build action buttons
  83. const actionButtons = `
  84. <div>
  85. ${vm.state === 'running' ? `
  86. <button class="btn btn-sm btn-warning" onclick="stopVM('${vmName}')">
  87. <i class="bi bi-stop-circle"></i> Detener
  88. </button>
  89. <button class="btn btn-sm btn-info" onclick="openConsole('${vmName}')">
  90. <i class="bi bi-display"></i> Consola
  91. </button>
  92. ` : `
  93. <button class="btn btn-sm btn-success" onclick="startVM('${vmName}')">
  94. <i class="bi bi-play-circle"></i> Iniciar
  95. </button>
  96. `}
  97. <button class="btn btn-sm btn-danger" onclick="deleteVMConfirm('${vmName}')">
  98. <i class="bi bi-trash"></i> Eliminar
  99. </button>
  100. </div>
  101. `;
  102. topBarActions.innerHTML = actionButtons;
  103. // Build content
  104. const disksHTML = vm.disks && vm.disks.length > 0 ? vm.disks.map(disk => `
  105. <li>
  106. <strong>${disk.target}</strong> (${disk.driver}) - ${disk.source}
  107. </li>
  108. `).join('') : '<li>Sin discos</li>';
  109. const interfacesHTML = vm.interfaces && vm.interfaces.length > 0 ? vm.interfaces.map(iface => `
  110. <li>
  111. <strong>MAC:</strong> ${iface.mac}<br>
  112. <strong>Red:</strong> ${iface.network}
  113. </li>
  114. `).join('') : '<li>Sin interfaces</li>';
  115. contentArea.innerHTML = `
  116. <ul class="nav nav-tabs" role="tablist">
  117. <li class="nav-item">
  118. <a class="nav-link active" id="overview-tab" data-bs-toggle="tab" href="#overview">Resumen</a>
  119. </li>
  120. <li class="nav-item">
  121. <a class="nav-link" id="disks-tab" data-bs-toggle="tab" href="#disks">Discos</a>
  122. </li>
  123. <li class="nav-item">
  124. <a class="nav-link" id="network-tab" data-bs-toggle="tab" href="#network">Red</a>
  125. </li>
  126. </ul>
  127. <div class="tab-content">
  128. <!-- Overview Tab -->
  129. <div class="tab-pane fade show active" id="overview">
  130. <div class="vm-details">
  131. <div class="card">
  132. <div class="card-header">
  133. <h6 class="card-title mb-0"><i class="bi bi-gear"></i> Configuración</h6>
  134. </div>
  135. <div class="card-body">
  136. <div class="info-item">
  137. <div class="info-label">ID de Dominio</div>
  138. <div class="info-value">${vm.id !== -1 ? vm.id : 'N/A (Parada)'}</div>
  139. </div>
  140. <div class="info-item">
  141. <div class="info-label">Estado</div>
  142. <div class="info-value">${statusBadge}</div>
  143. </div>
  144. <div class="info-item">
  145. <div class="info-label">Procesadores</div>
  146. <div class="info-value">${vm.cpus} CPU${vm.cpus !== 1 ? 's' : ''}</div>
  147. </div>
  148. <div class="info-item">
  149. <div class="info-label">Memoria RAM</div>
  150. <div class="info-value">${vm.memory} MiB</div>
  151. </div>
  152. </div>
  153. </div>
  154. <div class="card">
  155. <div class="card-header">
  156. <h6 class="card-title mb-0"><i class="bi bi-display"></i> Display</h6>
  157. </div>
  158. <div class="card-body">
  159. <div class="info-item">
  160. <div class="info-label">Puerto VNC</div>
  161. <div class="info-value">${vm.vnc_port ? vm.vnc_port : 'No asignado'}</div>
  162. </div>
  163. <div class="info-item">
  164. <div class="info-label">Dirección</div>
  165. <div class="info-value">${vm.vnc_port ? `localhost:${vm.vnc_port}` : 'N/A'}</div>
  166. </div>
  167. </div>
  168. </div>
  169. </div>
  170. <div class="actions-group">
  171. <h5><i class="bi bi-lightning"></i> Acciones</h5>
  172. <button class="btn btn-sm btn-primary btn-action" onclick="openBootOrderModal('${vmName}')">
  173. <i class="bi bi-arrow-repeat"></i> Configurar Arranque
  174. </button>
  175. <button class="btn btn-sm btn-info btn-action" onclick="openAddDiskModal('${vmName}')" ${vm.state !== 'shut off' ? 'disabled' : ''}>
  176. <i class="bi bi-plus-circle"></i> Agregar Disco
  177. </button>
  178. <button class="btn btn-sm btn-warning btn-action" onclick="openSnapshotModal('${vmName}')">
  179. <i class="bi bi-camera"></i> Crear Snapshot
  180. </button>
  181. <button class="btn btn-sm btn-secondary btn-action" onclick="openSnapshotsListModal('${vmName}')">
  182. <i class="bi bi-collection"></i> Ver Snapshots
  183. </button>
  184. <button class="btn btn-sm btn-secondary btn-action" onclick="downloadVMConfig('${vmName}')">
  185. <i class="bi bi-download"></i> Descargar XML
  186. </button>
  187. </div>
  188. </div>
  189. <!-- Disks Tab -->
  190. <div class="tab-pane fade" id="disks">
  191. <div class="card">
  192. <div class="card-header">
  193. <h6 class="card-title mb-0"><i class="bi bi-hdd"></i> Discos</h6>
  194. </div>
  195. <div class="card-body">
  196. <ul class="list-unstyled">
  197. ${disksHTML}
  198. </ul>
  199. </div>
  200. </div>
  201. </div>
  202. <!-- Network Tab -->
  203. <div class="tab-pane fade" id="network">
  204. <div class="card">
  205. <div class="card-header">
  206. <h6 class="card-title mb-0"><i class="bi bi-diagram-3"></i> Interfaces de Red</h6>
  207. </div>
  208. <div class="card-body">
  209. <ul class="list-unstyled">
  210. ${interfacesHTML}
  211. </ul>
  212. </div>
  213. </div>
  214. </div>
  215. </div>
  216. `;
  217. }
  218. // Show error message
  219. function showError(message) {
  220. const contentArea = document.getElementById('contentArea');
  221. contentArea.innerHTML = `
  222. <div class="alert alert-danger" role="alert">
  223. <i class="bi bi-exclamation-circle"></i> ${message}
  224. </div>
  225. `;
  226. }
  227. // Open Create VM Modal
  228. function openCreateVMModal() {
  229. const modal = new bootstrap.Modal(document.getElementById('createVMModal'));
  230. modal.show();
  231. }
  232. // Create VM
  233. async function createVM(e) {
  234. e.preventDefault();
  235. const name = document.getElementById('name').value;
  236. const memory = document.getElementById('memory').value;
  237. const disk_size = document.getElementById('disk_size').value;
  238. const cpus = document.getElementById('cpus').value;
  239. const iso = document.getElementById('iso').value;
  240. if (!iso) {
  241. alert('Por favor selecciona una ISO');
  242. return;
  243. }
  244. try {
  245. const response = await fetch(`${API_BASE}/vms?name=${name}&memory=${memory}&disk_size=${disk_size}&cpus=${cpus}&iso=${iso}`, {
  246. method: 'POST'
  247. });
  248. let result;
  249. try {
  250. result = await response.json();
  251. } catch {
  252. result = { error: `Server error: ${response.status}` };
  253. }
  254. if (response.ok) {
  255. alert(result.message || 'VM creada correctamente');
  256. document.getElementById('createVMForm').reset();
  257. bootstrap.Modal.getInstance(document.getElementById('createVMModal')).hide();
  258. loadVMs();
  259. } else {
  260. alert(result.error || 'Error al crear VM');
  261. }
  262. } catch (error) {
  263. console.error('Error:', error);
  264. alert(`Error: ${error.message}`);
  265. }
  266. }
  267. // Load ISOs for select
  268. async function loadISOsForSelect() {
  269. try {
  270. const response = await fetch(`${API_BASE}/isos`);
  271. const data = await response.json();
  272. const select = document.getElementById('iso');
  273. select.innerHTML = '<option value="">Selecciona una ISO</option>';
  274. if (data.isos && data.isos.length > 0) {
  275. data.isos.forEach(iso => {
  276. select.innerHTML += `<option value="${iso.path}">${iso.name}</option>`;
  277. });
  278. }
  279. } catch (error) {
  280. console.error('Error loading ISOs:', error);
  281. }
  282. }
  283. // Start VM
  284. async function startVM(vmName) {
  285. try {
  286. const response = await fetch(`${API_BASE}/vms/${vmName}/start`);
  287. const result = await response.json();
  288. if (response.ok) {
  289. loadVMs();
  290. if (selectedVM === vmName) {
  291. selectVM(vmName);
  292. }
  293. } else {
  294. alert(result.error || 'Error al iniciar VM');
  295. }
  296. } catch (error) {
  297. console.error('Error:', error);
  298. alert(`Error: ${error.message}`);
  299. }
  300. }
  301. // Stop VM
  302. async function stopVM(vmName) {
  303. if (confirm(`¿Estás seguro de que quieres detener ${vmName}?`)) {
  304. try {
  305. const response = await fetch(`${API_BASE}/vms/${vmName}/stop`);
  306. const result = await response.json();
  307. if (response.ok) {
  308. loadVMs();
  309. if (selectedVM === vmName) {
  310. selectVM(vmName);
  311. }
  312. } else {
  313. alert(result.error || 'Error al detener VM');
  314. }
  315. } catch (error) {
  316. console.error('Error:', error);
  317. alert(`Error: ${error.message}`);
  318. }
  319. }
  320. }
  321. // Delete VM
  322. async function deleteVMConfirm(vmName) {
  323. if (confirm(`¿Estás seguro de que quieres eliminar ${vmName}? Esta acción no se puede deshacer.`)) {
  324. try {
  325. const response = await fetch(`${API_BASE}/vms/${vmName}`, { method: 'DELETE' });
  326. const result = await response.json();
  327. if (response.ok) {
  328. alert('VM eliminada correctamente');
  329. selectedVM = null;
  330. loadVMs();
  331. document.getElementById('contentArea').innerHTML = `
  332. <div class="empty-state">
  333. <i class="bi bi-inbox"></i>
  334. <h5>Selecciona una máquina virtual</h5>
  335. <p>Haz clic en una VM del panel lateral para ver sus detalles</p>
  336. </div>
  337. `;
  338. } else {
  339. alert(result.error || 'Error al eliminar VM');
  340. }
  341. } catch (error) {
  342. console.error('Error:', error);
  343. alert(`Error: ${error.message}`);
  344. }
  345. }
  346. }
  347. // Open Boot Order Modal
  348. function openBootOrderModal(vmName) {
  349. const html = `
  350. <div class="modal fade" id="bootOrderModal" tabindex="-1">
  351. <div class="modal-dialog">
  352. <div class="modal-content">
  353. <div class="modal-header">
  354. <h5 class="modal-title">Configurar Orden de Arranque - ${vmName}</h5>
  355. <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
  356. </div>
  357. <form id="bootOrderForm">
  358. <div class="modal-body">
  359. <div class="mb-3">
  360. <label for="bootOrderInput" class="form-label">Orden de Arranque</label>
  361. <input type="text" class="form-control" id="bootOrderInput" placeholder="hd,cdrom" required>
  362. <small class="form-text text-muted">Separados por comas: hd, cdrom, network</small>
  363. </div>
  364. </div>
  365. <div class="modal-footer">
  366. <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
  367. <button type="submit" class="btn btn-primary">Guardar</button>
  368. </div>
  369. </form>
  370. </div>
  371. </div>
  372. </div>
  373. `;
  374. document.body.insertAdjacentHTML('beforeend', html);
  375. const modal = new bootstrap.Modal(document.getElementById('bootOrderModal'));
  376. document.getElementById('bootOrderForm').addEventListener('submit', async (e) => {
  377. e.preventDefault();
  378. const order = document.getElementById('bootOrderInput').value.split(',').map(s => s.trim());
  379. try {
  380. const response = await fetch(`${API_BASE}/vms/${vmName}/boot-order`, {
  381. method: 'PUT',
  382. headers: { 'Content-Type': 'application/json' },
  383. body: JSON.stringify({ order })
  384. });
  385. const result = await response.json();
  386. if (response.ok) {
  387. alert('Orden de arranque actualizado');
  388. modal.hide();
  389. document.getElementById('bootOrderModal').remove();
  390. } else {
  391. alert(result.error || 'Error al actualizar');
  392. }
  393. } catch (error) {
  394. alert(`Error: ${error.message}`);
  395. }
  396. });
  397. modal.show();
  398. }
  399. // Open Add Disk Modal
  400. function openAddDiskModal(vmName) {
  401. const html = `
  402. <div class="modal fade" id="addDiskModal" tabindex="-1">
  403. <div class="modal-dialog">
  404. <div class="modal-content">
  405. <div class="modal-header">
  406. <h5 class="modal-title">Agregar Disco - ${vmName}</h5>
  407. <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
  408. </div>
  409. <div class="alert alert-warning m-3">
  410. <small><strong>⚠️ Importante:</strong> La VM debe estar parada y el nombre del disco no debe existir</small>
  411. </div>
  412. <form id="addDiskFormModal">
  413. <div class="modal-body">
  414. <div class="mb-3">
  415. <label for="diskNameInput" class="form-label">Nombre del Disco</label>
  416. <input type="text" class="form-control" id="diskNameInput" placeholder="datos" required>
  417. </div>
  418. <div class="mb-3">
  419. <label for="diskSizeInput" class="form-label">Tamaño (GB)</label>
  420. <input type="number" class="form-control" id="diskSizeInput" value="10" min="1" required>
  421. </div>
  422. </div>
  423. <div class="modal-footer">
  424. <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
  425. <button type="submit" class="btn btn-primary">Agregar</button>
  426. </div>
  427. </form>
  428. </div>
  429. </div>
  430. </div>
  431. `;
  432. document.body.insertAdjacentHTML('beforeend', html);
  433. const modal = new bootstrap.Modal(document.getElementById('addDiskModal'));
  434. document.getElementById('addDiskFormModal').addEventListener('submit', async (e) => {
  435. e.preventDefault();
  436. const disk_name = document.getElementById('diskNameInput').value;
  437. const disk_size = document.getElementById('diskSizeInput').value;
  438. try {
  439. const response = await fetch(`${API_BASE}/vms/${vmName}/add-disk?disk_name=${disk_name}&disk_size=${disk_size}`, {
  440. method: 'POST'
  441. });
  442. let result;
  443. try {
  444. result = await response.json();
  445. } catch {
  446. result = { error: 'Error del servidor' };
  447. }
  448. if (response.ok) {
  449. alert(result.message || 'Disco agregado correctamente');
  450. modal.hide();
  451. document.getElementById('addDiskModal').remove();
  452. selectVM(vmName); // Refresh
  453. } else {
  454. alert(result.error || 'Error al agregar disco');
  455. }
  456. } catch (error) {
  457. alert(`Error: ${error.message}`);
  458. }
  459. });
  460. modal.show();
  461. }
  462. // Open Console
  463. function openConsole(vmName) {
  464. fetch(`${API_BASE}/console/${vmName}`)
  465. .then(response => response.json())
  466. .then(data => {
  467. if (data.url) {
  468. window.open(data.url);
  469. } else {
  470. alert(data.error || 'Error al abrir consola');
  471. }
  472. })
  473. .catch(error => {
  474. console.error('Error:', error);
  475. alert('Error al abrir consola');
  476. });
  477. }
  478. // Open ISO Management Modal
  479. function openISOManagementModal() {
  480. const modal = new bootstrap.Modal(document.getElementById('isoManagementModal'));
  481. loadISOs();
  482. setupUploadISOForm();
  483. modal.show();
  484. }
  485. // Load ISOs for management
  486. async function loadISOs() {
  487. try {
  488. const response = await fetch(`${API_BASE}/isos`);
  489. const data = await response.json();
  490. const tbody = document.getElementById('isoTableBody');
  491. if (!data.isos || data.isos.length === 0) {
  492. tbody.innerHTML = '<tr><td colspan="2" class="text-center text-muted">No hay ISOs subidas</td></tr>';
  493. return;
  494. }
  495. tbody.innerHTML = data.isos.map(iso => `
  496. <tr>
  497. <td>
  498. <i class="bi bi-disc"></i> ${iso.name}
  499. </td>
  500. <td>
  501. <button class="btn btn-sm btn-danger" onclick="deleteISO('${iso.name}')">
  502. <i class="bi bi-trash"></i> Eliminar
  503. </button>
  504. </td>
  505. </tr>
  506. `).join('');
  507. } catch (error) {
  508. console.error('Error loading ISOs:', error);
  509. document.getElementById('isoTableBody').innerHTML = '<tr><td colspan="2" class="text-center text-danger">Error al cargar ISOs</td></tr>';
  510. }
  511. }
  512. // Setup ISO upload form
  513. function setupUploadISOForm() {
  514. const form = document.getElementById('uploadIsoForm');
  515. if (!form.dataset.listenerAdded) {
  516. form.addEventListener('submit', uploadISO);
  517. form.dataset.listenerAdded = 'true';
  518. }
  519. }
  520. // Upload ISO
  521. async function uploadISO(e) {
  522. e.preventDefault();
  523. const isoFile = document.getElementById('isoFile');
  524. const uploadBtn = document.getElementById('uploadBtn');
  525. const progressContainer = document.getElementById('progressContainer');
  526. const uploadProgress = document.getElementById('uploadProgress');
  527. if (!isoFile.files.length) {
  528. alert('Por favor selecciona un archivo');
  529. return;
  530. }
  531. const formData = new FormData();
  532. formData.append('file', isoFile.files[0]);
  533. uploadBtn.disabled = true;
  534. progressContainer.style.display = 'block';
  535. try {
  536. const xhr = new XMLHttpRequest();
  537. xhr.upload.addEventListener('progress', (e) => {
  538. if (e.lengthComputable) {
  539. const percentComplete = (e.loaded / e.total) * 100;
  540. uploadProgress.style.width = percentComplete + '%';
  541. uploadProgress.setAttribute('aria-valuenow', percentComplete);
  542. uploadProgress.textContent = Math.round(percentComplete) + '%';
  543. }
  544. });
  545. xhr.addEventListener('load', () => {
  546. if (xhr.status === 200) {
  547. const result = JSON.parse(xhr.responseText);
  548. alert(result.message || 'ISO subida correctamente');
  549. document.getElementById('uploadIsoForm').reset();
  550. progressContainer.style.display = 'none';
  551. uploadProgress.style.width = '0%';
  552. uploadProgress.textContent = '0%';
  553. loadISOs();
  554. loadISOsForSelect();
  555. } else {
  556. const result = JSON.parse(xhr.responseText);
  557. alert(result.error || 'Error al subir ISO');
  558. progressContainer.style.display = 'none';
  559. }
  560. uploadBtn.disabled = false;
  561. });
  562. xhr.addEventListener('error', () => {
  563. alert('Error al subir ISO');
  564. progressContainer.style.display = 'none';
  565. uploadBtn.disabled = false;
  566. });
  567. xhr.open('POST', `${API_BASE}/upload-iso`);
  568. xhr.send(formData);
  569. } catch (error) {
  570. console.error('Error:', error);
  571. alert(`Error: ${error.message}`);
  572. uploadBtn.disabled = false;
  573. progressContainer.style.display = 'none';
  574. }
  575. }
  576. // Delete ISO
  577. async function deleteISO(name) {
  578. if (confirm(`¿Estás seguro de que quieres eliminar ${name}?`)) {
  579. try {
  580. const response = await fetch(`${API_BASE}/isos/${name}`, { method: 'DELETE' });
  581. const result = await response.json();
  582. if (response.ok) {
  583. alert('ISO eliminada correctamente');
  584. loadISOs();
  585. loadISOsForSelect();
  586. } else {
  587. alert(result.error || 'Error al eliminar ISO');
  588. }
  589. } catch (error) {
  590. console.error('Error:', error);
  591. alert(`Error: ${error.message}`);
  592. }
  593. }
  594. }
  595. // Mobile responsive - Toggle sidebar
  596. function toggleSidebar() {
  597. const sidebar = document.querySelector('.sidebar');
  598. // Para móviles (max-width 768px), mostrar/ocultar el sidebar
  599. if (window.innerWidth <= 768) {
  600. sidebar.classList.toggle('show');
  601. }
  602. }
  603. // Cerrar sidebar cuando se selecciona una VM en móvil
  604. const originalSelectVM = window.selectVM;
  605. window.selectVM = function(vmName) {
  606. originalSelectVM(vmName);
  607. // Cerrar sidebar en móvil después de seleccionar
  608. if (window.innerWidth <= 768) {
  609. const sidebar = document.querySelector('.sidebar');
  610. sidebar.classList.remove('show');
  611. }
  612. };
  613. // Cerrar sidebar cuando se abre un modal
  614. document.addEventListener('shown.bs.modal', function() {
  615. if (window.innerWidth <= 768) {
  616. const sidebar = document.querySelector('.sidebar');
  617. sidebar.classList.remove('show');
  618. }
  619. });
  620. // Download VM configuration as XML
  621. async function downloadVMConfig(vmName) {
  622. try {
  623. const response = await fetch(`${API_BASE}/vms/${vmName}/config`);
  624. if (!response.ok) {
  625. alert(`Error: El servidor respondió con estado ${response.status}`);
  626. return;
  627. }
  628. const data = await response.json();
  629. if (data.error) {
  630. alert(`Error: ${data.error}`);
  631. return;
  632. }
  633. // Validar que tenemos el contenido XML
  634. if (!data.xml || data.xml === undefined || data.xml === 'undefined') {
  635. console.error('XML content is undefined or missing:', data);
  636. alert('Error: No se pudo obtener la configuración XML');
  637. return;
  638. }
  639. // Create a blob with the XML content
  640. const blob = new Blob([data.xml], { type: 'application/xml' });
  641. const url = window.URL.createObjectURL(blob);
  642. const link = document.createElement('a');
  643. link.href = url;
  644. link.download = `${vmName}-config.xml`;
  645. document.body.appendChild(link);
  646. link.click();
  647. document.body.removeChild(link);
  648. window.URL.revokeObjectURL(url);
  649. } catch (error) {
  650. console.error('Error downloading config:', error);
  651. alert(`Error al descargar configuración: ${error.message}`);
  652. }
  653. }
  654. // Open snapshot modal
  655. function openSnapshotModal(vmName) {
  656. const modal = document.createElement('div');
  657. modal.classList.add('modal', 'fade');
  658. modal.innerHTML = `
  659. <div class="modal-dialog">
  660. <div class="modal-content">
  661. <div class="modal-header">
  662. <h5 class="modal-title">Crear Snapshot - ${vmName}</h5>
  663. <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
  664. </div>
  665. <div class="modal-body">
  666. <div class="mb-3">
  667. <label for="snapshotName" class="form-label">Nombre del Snapshot</label>
  668. <input type="text" class="form-control" id="snapshotName" placeholder="ej: snapshot-2026-01-18" required>
  669. </div>
  670. <div class="mb-3">
  671. <label for="snapshotDesc" class="form-label">Descripción (opcional)</label>
  672. <textarea class="form-control" id="snapshotDesc" rows="3" placeholder="Describe el propósito de este snapshot"></textarea>
  673. </div>
  674. </div>
  675. <div class="modal-footer">
  676. <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
  677. <button type="button" class="btn btn-warning" onclick="createSnapshot('${vmName}')">
  678. <i class="bi bi-camera"></i> Crear Snapshot
  679. </button>
  680. </div>
  681. </div>
  682. </div>
  683. `;
  684. document.body.appendChild(modal);
  685. const bsModal = new bootstrap.Modal(modal);
  686. bsModal.show();
  687. // Limpiar modal al cerrarlo
  688. modal.addEventListener('hidden.bs.modal', () => {
  689. modal.remove();
  690. });
  691. }
  692. // Create snapshot
  693. async function createSnapshot(vmName) {
  694. const snapshotName = document.getElementById('snapshotName').value.trim();
  695. const snapshotDesc = document.getElementById('snapshotDesc').value.trim();
  696. if (!snapshotName) {
  697. alert('El nombre del snapshot es obligatorio');
  698. return;
  699. }
  700. // Validar que el nombre sea válido (sin espacios ni caracteres especiales)
  701. if (!/^[a-zA-Z0-9._-]+$/.test(snapshotName)) {
  702. alert('El nombre del snapshot solo puede contener letras, números, puntos, guiones y guiones bajos');
  703. return;
  704. }
  705. try {
  706. const url = new URL(`${API_BASE}/vms/${vmName}/snapshot`);
  707. url.searchParams.append('snapshot_name', snapshotName);
  708. if (snapshotDesc) {
  709. url.searchParams.append('description', snapshotDesc);
  710. }
  711. const response = await fetch(url, { method: 'POST' });
  712. const data = await response.json();
  713. if (data.error) {
  714. alert(`Error: ${data.error}`);
  715. return;
  716. }
  717. alert(`✓ Snapshot "${snapshotName}" creado exitosamente`);
  718. // Cerrar modal - buscar el modal visible
  719. const visibleModal = document.querySelector('.modal.show');
  720. if (visibleModal) {
  721. const modalInstance = bootstrap.Modal.getInstance(visibleModal);
  722. if (modalInstance) {
  723. modalInstance.hide();
  724. }
  725. }
  726. } catch (error) {
  727. console.error('Error:', error);
  728. alert(`Error al crear snapshot: ${error.message}`);
  729. }
  730. }
  731. // Open snapshots list modal
  732. function openSnapshotsListModal(vmName) {
  733. const modal = document.createElement('div');
  734. modal.classList.add('modal', 'fade');
  735. modal.innerHTML = `
  736. <div class="modal-dialog modal-lg">
  737. <div class="modal-content">
  738. <div class="modal-header">
  739. <h5 class="modal-title">Snapshots - ${vmName}</h5>
  740. <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
  741. </div>
  742. <div class="modal-body">
  743. <div id="snapshotsList" class="text-center">
  744. <p class="text-muted">Cargando snapshots...</p>
  745. </div>
  746. </div>
  747. <div class="modal-footer">
  748. <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
  749. </div>
  750. </div>
  751. </div>
  752. `;
  753. document.body.appendChild(modal);
  754. const bsModal = new bootstrap.Modal(modal);
  755. bsModal.show();
  756. // Limpiar modal al cerrarlo
  757. modal.addEventListener('hidden.bs.modal', () => {
  758. modal.remove();
  759. });
  760. // Cargar snapshots
  761. loadSnapshotsList(vmName);
  762. }
  763. // Load and display snapshots list
  764. async function loadSnapshotsList(vmName) {
  765. try {
  766. const response = await fetch(`${API_BASE}/vms/${vmName}/snapshots`);
  767. const data = await response.json();
  768. if (data.error) {
  769. document.getElementById('snapshotsList').innerHTML = `<p class="text-danger">Error: ${data.error}</p>`;
  770. return;
  771. }
  772. const snapshots = data.snapshots;
  773. if (!snapshots || snapshots.length === 0) {
  774. document.getElementById('snapshotsList').innerHTML = '<p class="text-muted">No hay snapshots disponibles</p>';
  775. return;
  776. }
  777. let html = `
  778. <div class="table-responsive">
  779. <table class="table table-sm table-hover">
  780. <thead>
  781. <tr>
  782. <th>Nombre</th>
  783. <th>Creado</th>
  784. <th>Descripción</th>
  785. <th>Estado</th>
  786. <th>Acciones</th>
  787. </tr>
  788. </thead>
  789. <tbody>
  790. `;
  791. snapshots.forEach(snap => {
  792. let created = 'Desconocida';
  793. if (snap.created && snap.created > 0) {
  794. created = new Date(snap.created * 1000).toLocaleString('es-ES');
  795. }
  796. html += `
  797. <tr>
  798. <td><strong>${snap.name}</strong></td>
  799. <td>${created}</td>
  800. <td>${snap.description || '-'}</td>
  801. <td><span class="badge bg-info">${snap.state}</span></td>
  802. <td>
  803. <button class="btn btn-sm btn-danger" onclick="deleteSnapshotConfirm('${vmName}', '${snap.name}')">
  804. <i class="bi bi-trash"></i> Eliminar
  805. </button>
  806. </td>
  807. </tr>
  808. `;
  809. });
  810. html += `
  811. </tbody>
  812. </table>
  813. </div>
  814. `;
  815. document.getElementById('snapshotsList').innerHTML = html;
  816. } catch (error) {
  817. console.error('Error:', error);
  818. document.getElementById('snapshotsList').innerHTML = `<p class="text-danger">Error: ${error.message}</p>`;
  819. }
  820. }
  821. // Delete snapshot with confirmation
  822. function deleteSnapshotConfirm(vmName, snapshotName) {
  823. if (confirm(`¿Estás seguro de que deseas eliminar el snapshot "${snapshotName}"?`)) {
  824. deleteSnapshot(vmName, snapshotName);
  825. }
  826. }
  827. // Delete snapshot
  828. async function deleteSnapshot(vmName, snapshotName) {
  829. try {
  830. const encodedSnapshotName = encodeURIComponent(snapshotName);
  831. const response = await fetch(`${API_BASE}/vms/${vmName}/snapshots/${encodedSnapshotName}`, {
  832. method: 'DELETE'
  833. });
  834. const data = await response.json();
  835. if (data.error) {
  836. alert(`Error: ${data.error}`);
  837. return;
  838. }
  839. alert(`✓ Snapshot "${snapshotName}" eliminado exitosamente`);
  840. // Recargar lista de snapshots
  841. loadSnapshotsList(vmName);
  842. } catch (error) {
  843. console.error('Error:', error);
  844. alert(`Error al eliminar snapshot: ${error.message}`);
  845. }
  846. }