dashboard.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241
  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. // Clean up previous charts
  62. cleanupCharts();
  63. try {
  64. const response = await fetch(`${API_BASE}/vms/${vmName}/info`);
  65. const vm = await response.json();
  66. if (vm.error) {
  67. showError(vm.error);
  68. return;
  69. }
  70. displayVMDetails(vm, vmName);
  71. // Initialize performance charts only if VM is running
  72. if (vm.state === 'running') {
  73. setTimeout(() => initializePerformanceCharts(vmName), 100);
  74. }
  75. } catch (error) {
  76. console.error('Error loading VM info:', error);
  77. showError('Error al cargar información de la VM');
  78. }
  79. }
  80. // Display VM details
  81. function displayVMDetails(vm, vmName) {
  82. const contentArea = document.getElementById('contentArea');
  83. const topBar = document.getElementById('currentVMName');
  84. const topBarActions = document.getElementById('topBarActions');
  85. topBar.textContent = vmName;
  86. // Build status badge
  87. const statusBadge = `<span class="badge ${getStateClass(vm.state)} p-2">${vm.state}</span>`;
  88. // Build action buttons
  89. const actionButtons = `
  90. <div>
  91. ${vm.state === 'running' ? `
  92. <button class="btn btn-sm btn-warning" onclick="stopVM('${vmName}')">
  93. <i class="bi bi-stop-circle"></i> Detener
  94. </button>
  95. <button class="btn btn-sm btn-info" onclick="openConsole('${vmName}')">
  96. <i class="bi bi-display"></i> Consola
  97. </button>
  98. ` : `
  99. <button class="btn btn-sm btn-success" onclick="startVM('${vmName}')">
  100. <i class="bi bi-play-circle"></i> Iniciar
  101. </button>
  102. `}
  103. <button class="btn btn-sm btn-danger" onclick="deleteVMConfirm('${vmName}')">
  104. <i class="bi bi-trash"></i> Eliminar
  105. </button>
  106. </div>
  107. `;
  108. topBarActions.innerHTML = actionButtons;
  109. // Build content
  110. const disksHTML = vm.disks && vm.disks.length > 0 ? vm.disks.map(disk => `
  111. <li>
  112. <strong>${disk.target}</strong> (${disk.driver}) - ${disk.source}
  113. </li>
  114. `).join('') : '<li>Sin discos</li>';
  115. const interfacesHTML = vm.interfaces && vm.interfaces.length > 0 ? vm.interfaces.map(iface => `
  116. <li>
  117. <strong>MAC:</strong> ${iface.mac}<br>
  118. <strong>Red:</strong> ${iface.network}
  119. </li>
  120. `).join('') : '<li>Sin interfaces</li>';
  121. contentArea.innerHTML = `
  122. <ul class="nav nav-tabs" role="tablist">
  123. <li class="nav-item">
  124. <a class="nav-link active" id="overview-tab" data-bs-toggle="tab" href="#overview">Resumen</a>
  125. </li>
  126. <li class="nav-item">
  127. <a class="nav-link" id="disks-tab" data-bs-toggle="tab" href="#disks">Discos</a>
  128. </li>
  129. <li class="nav-item">
  130. <a class="nav-link" id="network-tab" data-bs-toggle="tab" href="#network">Red</a>
  131. </li>
  132. </ul>
  133. <div class="tab-content">
  134. <!-- Overview Tab -->
  135. <div class="tab-pane fade show active" id="overview">
  136. <div class="vm-details">
  137. <div class="card">
  138. <div class="card-header">
  139. <h6 class="card-title mb-0"><i class="bi bi-gear"></i> Configuración</h6>
  140. </div>
  141. <div class="card-body">
  142. <div class="info-item">
  143. <div class="info-label">ID de Dominio</div>
  144. <div class="info-value">${vm.id !== -1 ? vm.id : 'N/A (Parada)'}</div>
  145. </div>
  146. <div class="info-item">
  147. <div class="info-label">Estado</div>
  148. <div class="info-value">${statusBadge}</div>
  149. </div>
  150. <div class="info-item">
  151. <div class="info-label">Procesadores</div>
  152. <div class="info-value">${vm.cpus} CPU${vm.cpus !== 1 ? 's' : ''}</div>
  153. </div>
  154. <div class="info-item">
  155. <div class="info-label">Memoria RAM</div>
  156. <div class="info-value">${vm.memory} MiB</div>
  157. </div>
  158. </div>
  159. </div>
  160. <div class="card">
  161. <div class="card-header">
  162. <h6 class="card-title mb-0"><i class="bi bi-display"></i> Display</h6>
  163. </div>
  164. <div class="card-body">
  165. <div class="info-item">
  166. <div class="info-label">Puerto VNC</div>
  167. <div class="info-value">${vm.vnc_port ? vm.vnc_port : 'No asignado'}</div>
  168. </div>
  169. <div class="info-item">
  170. <div class="info-label">Dirección</div>
  171. <div class="info-value">${vm.vnc_port ? `localhost:${vm.vnc_port}` : 'N/A'}</div>
  172. </div>
  173. </div>
  174. </div>
  175. <!-- Performance Charts -->
  176. ${vm.state === 'running' ? `
  177. <div class="card">
  178. <div class="card-header">
  179. <h6 class="card-title mb-0"><i class="bi bi-graph-up"></i> Rendimiento</h6>
  180. </div>
  181. <div class="card-body">
  182. <div class="row">
  183. <div class="col-md-6">
  184. <div style="position: relative; height: 250px;">
  185. <canvas id="cpuChart"></canvas>
  186. </div>
  187. </div>
  188. <div class="col-md-6">
  189. <div style="position: relative; height: 250px;">
  190. <canvas id="memoryChart"></canvas>
  191. </div>
  192. </div>
  193. </div>
  194. </div>
  195. </div>
  196. ` : ''}
  197. </div>
  198. <div class="actions-group">
  199. <h5><i class="bi bi-lightning"></i> Acciones</h5>
  200. <button class="btn btn-sm btn-primary btn-action" onclick="openBootOrderModal('${vmName}')">
  201. <i class="bi bi-arrow-repeat"></i> Configurar Arranque
  202. </button>
  203. <button class="btn btn-sm btn-info btn-action" onclick="openAddDiskModal('${vmName}')" ${vm.state !== 'shut off' ? 'disabled' : ''}>
  204. <i class="bi bi-plus-circle"></i> Agregar Disco
  205. </button>
  206. <button class="btn btn-sm btn-warning btn-action" onclick="openSnapshotModal('${vmName}')">
  207. <i class="bi bi-camera"></i> Crear Snapshot
  208. </button>
  209. <button class="btn btn-sm btn-secondary btn-action" onclick="openSnapshotsListModal('${vmName}')">
  210. <i class="bi bi-collection"></i> Ver Snapshots
  211. </button>
  212. <button class="btn btn-sm btn-secondary btn-action" onclick="downloadVMConfig('${vmName}')">
  213. <i class="bi bi-download"></i> Descargar XML
  214. </button>
  215. </div>
  216. </div>
  217. <!-- Disks Tab -->
  218. <div class="tab-pane fade" id="disks">
  219. <div class="card">
  220. <div class="card-header">
  221. <h6 class="card-title mb-0"><i class="bi bi-hdd"></i> Discos</h6>
  222. </div>
  223. <div class="card-body">
  224. <ul class="list-unstyled">
  225. ${disksHTML}
  226. </ul>
  227. </div>
  228. </div>
  229. </div>
  230. <!-- Network Tab -->
  231. <div class="tab-pane fade" id="network">
  232. <div class="card">
  233. <div class="card-header">
  234. <h6 class="card-title mb-0"><i class="bi bi-diagram-3"></i> Interfaces de Red</h6>
  235. </div>
  236. <div class="card-body">
  237. <ul class="list-unstyled">
  238. ${interfacesHTML}
  239. </ul>
  240. </div>
  241. </div>
  242. </div>
  243. </div>
  244. `;
  245. }
  246. // Show error message
  247. function showError(message) {
  248. const contentArea = document.getElementById('contentArea');
  249. contentArea.innerHTML = `
  250. <div class="alert alert-danger" role="alert">
  251. <i class="bi bi-exclamation-circle"></i> ${message}
  252. </div>
  253. `;
  254. }
  255. // Open Create VM Modal
  256. function openCreateVMModal() {
  257. const modal = new bootstrap.Modal(document.getElementById('createVMModal'));
  258. modal.show();
  259. }
  260. // Create VM
  261. async function createVM(e) {
  262. e.preventDefault();
  263. const name = document.getElementById('name').value;
  264. const memory = document.getElementById('memory').value;
  265. const disk_size = document.getElementById('disk_size').value;
  266. const cpus = document.getElementById('cpus').value;
  267. const iso = document.getElementById('iso').value;
  268. if (!iso) {
  269. alert('Por favor selecciona una ISO');
  270. return;
  271. }
  272. try {
  273. const response = await fetch(`${API_BASE}/vms?name=${name}&memory=${memory}&disk_size=${disk_size}&cpus=${cpus}&iso=${iso}`, {
  274. method: 'POST'
  275. });
  276. let result;
  277. try {
  278. result = await response.json();
  279. } catch {
  280. result = { error: `Server error: ${response.status}` };
  281. }
  282. if (response.ok) {
  283. alert(result.message || 'VM creada correctamente');
  284. document.getElementById('createVMForm').reset();
  285. bootstrap.Modal.getInstance(document.getElementById('createVMModal')).hide();
  286. loadVMs();
  287. } else {
  288. alert(result.error || 'Error al crear VM');
  289. }
  290. } catch (error) {
  291. console.error('Error:', error);
  292. alert(`Error: ${error.message}`);
  293. }
  294. }
  295. // Load ISOs for select
  296. async function loadISOsForSelect() {
  297. try {
  298. const response = await fetch(`${API_BASE}/isos`);
  299. const data = await response.json();
  300. const select = document.getElementById('iso');
  301. select.innerHTML = '<option value="">Selecciona una ISO</option>';
  302. if (data.isos && data.isos.length > 0) {
  303. data.isos.forEach(iso => {
  304. select.innerHTML += `<option value="${iso.path}">${iso.name}</option>`;
  305. });
  306. }
  307. } catch (error) {
  308. console.error('Error loading ISOs:', error);
  309. }
  310. }
  311. // Start VM
  312. async function startVM(vmName) {
  313. try {
  314. const response = await fetch(`${API_BASE}/vms/${vmName}/start`);
  315. const result = await response.json();
  316. if (response.ok) {
  317. loadVMs();
  318. if (selectedVM === vmName) {
  319. selectVM(vmName);
  320. }
  321. } else {
  322. alert(result.error || 'Error al iniciar VM');
  323. }
  324. } catch (error) {
  325. console.error('Error:', error);
  326. alert(`Error: ${error.message}`);
  327. }
  328. }
  329. // Stop VM
  330. async function stopVM(vmName) {
  331. if (confirm(`¿Estás seguro de que quieres detener ${vmName}?`)) {
  332. try {
  333. const response = await fetch(`${API_BASE}/vms/${vmName}/stop`);
  334. const result = await response.json();
  335. if (response.ok) {
  336. loadVMs();
  337. if (selectedVM === vmName) {
  338. selectVM(vmName);
  339. }
  340. } else {
  341. alert(result.error || 'Error al detener VM');
  342. }
  343. } catch (error) {
  344. console.error('Error:', error);
  345. alert(`Error: ${error.message}`);
  346. }
  347. }
  348. }
  349. // Delete VM
  350. async function deleteVMConfirm(vmName) {
  351. if (confirm(`¿Estás seguro de que quieres eliminar ${vmName}? Esta acción no se puede deshacer.`)) {
  352. try {
  353. const response = await fetch(`${API_BASE}/vms/${vmName}`, { method: 'DELETE' });
  354. const result = await response.json();
  355. if (response.ok) {
  356. alert('VM eliminada correctamente');
  357. selectedVM = null;
  358. loadVMs();
  359. document.getElementById('contentArea').innerHTML = `
  360. <div class="empty-state">
  361. <i class="bi bi-inbox"></i>
  362. <h5>Selecciona una máquina virtual</h5>
  363. <p>Haz clic en una VM del panel lateral para ver sus detalles</p>
  364. </div>
  365. `;
  366. } else {
  367. alert(result.error || 'Error al eliminar VM');
  368. }
  369. } catch (error) {
  370. console.error('Error:', error);
  371. alert(`Error: ${error.message}`);
  372. }
  373. }
  374. }
  375. // Open Boot Order Modal
  376. function openBootOrderModal(vmName) {
  377. const html = `
  378. <div class="modal fade" id="bootOrderModal" tabindex="-1">
  379. <div class="modal-dialog">
  380. <div class="modal-content">
  381. <div class="modal-header">
  382. <h5 class="modal-title">Configurar Orden de Arranque - ${vmName}</h5>
  383. <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
  384. </div>
  385. <form id="bootOrderForm">
  386. <div class="modal-body">
  387. <div class="mb-3">
  388. <label for="bootOrderInput" class="form-label">Orden de Arranque</label>
  389. <input type="text" class="form-control" id="bootOrderInput" placeholder="hd,cdrom" required>
  390. <small class="form-text text-muted">Separados por comas: hd, cdrom, network</small>
  391. </div>
  392. </div>
  393. <div class="modal-footer">
  394. <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
  395. <button type="submit" class="btn btn-primary">Guardar</button>
  396. </div>
  397. </form>
  398. </div>
  399. </div>
  400. </div>
  401. `;
  402. document.body.insertAdjacentHTML('beforeend', html);
  403. const modal = new bootstrap.Modal(document.getElementById('bootOrderModal'));
  404. document.getElementById('bootOrderForm').addEventListener('submit', async (e) => {
  405. e.preventDefault();
  406. const order = document.getElementById('bootOrderInput').value.split(',').map(s => s.trim());
  407. try {
  408. const response = await fetch(`${API_BASE}/vms/${vmName}/boot-order`, {
  409. method: 'PUT',
  410. headers: { 'Content-Type': 'application/json' },
  411. body: JSON.stringify({ order })
  412. });
  413. const result = await response.json();
  414. if (response.ok) {
  415. alert('Orden de arranque actualizado');
  416. modal.hide();
  417. document.getElementById('bootOrderModal').remove();
  418. } else {
  419. alert(result.error || 'Error al actualizar');
  420. }
  421. } catch (error) {
  422. alert(`Error: ${error.message}`);
  423. }
  424. });
  425. modal.show();
  426. }
  427. // Open Add Disk Modal
  428. function openAddDiskModal(vmName) {
  429. const html = `
  430. <div class="modal fade" id="addDiskModal" tabindex="-1">
  431. <div class="modal-dialog">
  432. <div class="modal-content">
  433. <div class="modal-header">
  434. <h5 class="modal-title">Agregar Disco - ${vmName}</h5>
  435. <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
  436. </div>
  437. <div class="alert alert-warning m-3">
  438. <small><strong>⚠️ Importante:</strong> La VM debe estar parada y el nombre del disco no debe existir</small>
  439. </div>
  440. <form id="addDiskFormModal">
  441. <div class="modal-body">
  442. <div class="mb-3">
  443. <label for="diskNameInput" class="form-label">Nombre del Disco</label>
  444. <input type="text" class="form-control" id="diskNameInput" placeholder="datos" required>
  445. </div>
  446. <div class="mb-3">
  447. <label for="diskSizeInput" class="form-label">Tamaño (GB)</label>
  448. <input type="number" class="form-control" id="diskSizeInput" value="10" min="1" required>
  449. </div>
  450. </div>
  451. <div class="modal-footer">
  452. <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
  453. <button type="submit" class="btn btn-primary">Agregar</button>
  454. </div>
  455. </form>
  456. </div>
  457. </div>
  458. </div>
  459. `;
  460. document.body.insertAdjacentHTML('beforeend', html);
  461. const modal = new bootstrap.Modal(document.getElementById('addDiskModal'));
  462. document.getElementById('addDiskFormModal').addEventListener('submit', async (e) => {
  463. e.preventDefault();
  464. const disk_name = document.getElementById('diskNameInput').value;
  465. const disk_size = document.getElementById('diskSizeInput').value;
  466. try {
  467. const response = await fetch(`${API_BASE}/vms/${vmName}/add-disk?disk_name=${disk_name}&disk_size=${disk_size}`, {
  468. method: 'POST'
  469. });
  470. let result;
  471. try {
  472. result = await response.json();
  473. } catch {
  474. result = { error: 'Error del servidor' };
  475. }
  476. if (response.ok) {
  477. alert(result.message || 'Disco agregado correctamente');
  478. modal.hide();
  479. document.getElementById('addDiskModal').remove();
  480. selectVM(vmName); // Refresh
  481. } else {
  482. alert(result.error || 'Error al agregar disco');
  483. }
  484. } catch (error) {
  485. alert(`Error: ${error.message}`);
  486. }
  487. });
  488. modal.show();
  489. }
  490. // Open Console
  491. function openConsole(vmName) {
  492. fetch(`${API_BASE}/console/${vmName}`)
  493. .then(response => response.json())
  494. .then(data => {
  495. if (data.url) {
  496. window.open(data.url);
  497. } else {
  498. alert(data.error || 'Error al abrir consola');
  499. }
  500. })
  501. .catch(error => {
  502. console.error('Error:', error);
  503. alert('Error al abrir consola');
  504. });
  505. }
  506. // Open ISO Management Modal
  507. function openISOManagementModal() {
  508. const modal = new bootstrap.Modal(document.getElementById('isoManagementModal'));
  509. loadISOs();
  510. setupUploadISOForm();
  511. modal.show();
  512. }
  513. // Load ISOs for management
  514. async function loadISOs() {
  515. try {
  516. const response = await fetch(`${API_BASE}/isos`);
  517. const data = await response.json();
  518. const tbody = document.getElementById('isoTableBody');
  519. if (!data.isos || data.isos.length === 0) {
  520. tbody.innerHTML = '<tr><td colspan="2" class="text-center text-muted">No hay ISOs subidas</td></tr>';
  521. return;
  522. }
  523. tbody.innerHTML = data.isos.map(iso => `
  524. <tr>
  525. <td>
  526. <i class="bi bi-disc"></i> ${iso.name}
  527. </td>
  528. <td>
  529. <button class="btn btn-sm btn-danger" onclick="deleteISO('${iso.name}')">
  530. <i class="bi bi-trash"></i> Eliminar
  531. </button>
  532. </td>
  533. </tr>
  534. `).join('');
  535. } catch (error) {
  536. console.error('Error loading ISOs:', error);
  537. document.getElementById('isoTableBody').innerHTML = '<tr><td colspan="2" class="text-center text-danger">Error al cargar ISOs</td></tr>';
  538. }
  539. }
  540. // Setup ISO upload form
  541. function setupUploadISOForm() {
  542. const form = document.getElementById('uploadIsoForm');
  543. if (!form.dataset.listenerAdded) {
  544. form.addEventListener('submit', uploadISO);
  545. form.dataset.listenerAdded = 'true';
  546. }
  547. }
  548. // Upload ISO
  549. async function uploadISO(e) {
  550. e.preventDefault();
  551. const isoFile = document.getElementById('isoFile');
  552. const uploadBtn = document.getElementById('uploadBtn');
  553. const progressContainer = document.getElementById('progressContainer');
  554. const uploadProgress = document.getElementById('uploadProgress');
  555. if (!isoFile.files.length) {
  556. alert('Por favor selecciona un archivo');
  557. return;
  558. }
  559. const formData = new FormData();
  560. formData.append('file', isoFile.files[0]);
  561. uploadBtn.disabled = true;
  562. progressContainer.style.display = 'block';
  563. try {
  564. const xhr = new XMLHttpRequest();
  565. xhr.upload.addEventListener('progress', (e) => {
  566. if (e.lengthComputable) {
  567. const percentComplete = (e.loaded / e.total) * 100;
  568. uploadProgress.style.width = percentComplete + '%';
  569. uploadProgress.setAttribute('aria-valuenow', percentComplete);
  570. uploadProgress.textContent = Math.round(percentComplete) + '%';
  571. }
  572. });
  573. xhr.addEventListener('load', () => {
  574. if (xhr.status === 200) {
  575. const result = JSON.parse(xhr.responseText);
  576. alert(result.message || 'ISO subida correctamente');
  577. document.getElementById('uploadIsoForm').reset();
  578. progressContainer.style.display = 'none';
  579. uploadProgress.style.width = '0%';
  580. uploadProgress.textContent = '0%';
  581. loadISOs();
  582. loadISOsForSelect();
  583. } else {
  584. const result = JSON.parse(xhr.responseText);
  585. alert(result.error || 'Error al subir ISO');
  586. progressContainer.style.display = 'none';
  587. }
  588. uploadBtn.disabled = false;
  589. });
  590. xhr.addEventListener('error', () => {
  591. alert('Error al subir ISO');
  592. progressContainer.style.display = 'none';
  593. uploadBtn.disabled = false;
  594. });
  595. xhr.open('POST', `${API_BASE}/upload-iso`);
  596. xhr.send(formData);
  597. } catch (error) {
  598. console.error('Error:', error);
  599. alert(`Error: ${error.message}`);
  600. uploadBtn.disabled = false;
  601. progressContainer.style.display = 'none';
  602. }
  603. }
  604. // Delete ISO
  605. async function deleteISO(name) {
  606. if (confirm(`¿Estás seguro de que quieres eliminar ${name}?`)) {
  607. try {
  608. const response = await fetch(`${API_BASE}/isos/${name}`, { method: 'DELETE' });
  609. const result = await response.json();
  610. if (response.ok) {
  611. alert('ISO eliminada correctamente');
  612. loadISOs();
  613. loadISOsForSelect();
  614. } else {
  615. alert(result.error || 'Error al eliminar ISO');
  616. }
  617. } catch (error) {
  618. console.error('Error:', error);
  619. alert(`Error: ${error.message}`);
  620. }
  621. }
  622. }
  623. // Mobile responsive - Toggle sidebar
  624. function toggleSidebar() {
  625. const sidebar = document.querySelector('.sidebar');
  626. // Para móviles (max-width 768px), mostrar/ocultar el sidebar
  627. if (window.innerWidth <= 768) {
  628. sidebar.classList.toggle('show');
  629. }
  630. }
  631. // Cerrar sidebar cuando se selecciona una VM en móvil
  632. const originalSelectVM = window.selectVM;
  633. window.selectVM = function(vmName) {
  634. originalSelectVM(vmName);
  635. // Cerrar sidebar en móvil después de seleccionar
  636. if (window.innerWidth <= 768) {
  637. const sidebar = document.querySelector('.sidebar');
  638. sidebar.classList.remove('show');
  639. }
  640. };
  641. // Cerrar sidebar cuando se abre un modal
  642. document.addEventListener('shown.bs.modal', function() {
  643. if (window.innerWidth <= 768) {
  644. const sidebar = document.querySelector('.sidebar');
  645. sidebar.classList.remove('show');
  646. }
  647. });
  648. // Download VM configuration as XML
  649. async function downloadVMConfig(vmName) {
  650. try {
  651. const response = await fetch(`${API_BASE}/vms/${vmName}/config`);
  652. if (!response.ok) {
  653. alert(`Error: El servidor respondió con estado ${response.status}`);
  654. return;
  655. }
  656. const data = await response.json();
  657. if (data.error) {
  658. alert(`Error: ${data.error}`);
  659. return;
  660. }
  661. // Validar que tenemos el contenido XML
  662. if (!data.xml || data.xml === undefined || data.xml === 'undefined') {
  663. console.error('XML content is undefined or missing:', data);
  664. alert('Error: No se pudo obtener la configuración XML');
  665. return;
  666. }
  667. // Create a blob with the XML content
  668. const blob = new Blob([data.xml], { type: 'application/xml' });
  669. const url = window.URL.createObjectURL(blob);
  670. const link = document.createElement('a');
  671. link.href = url;
  672. link.download = `${vmName}-config.xml`;
  673. document.body.appendChild(link);
  674. link.click();
  675. document.body.removeChild(link);
  676. window.URL.revokeObjectURL(url);
  677. } catch (error) {
  678. console.error('Error downloading config:', error);
  679. alert(`Error al descargar configuración: ${error.message}`);
  680. }
  681. }
  682. // Open snapshot modal
  683. function openSnapshotModal(vmName) {
  684. const modal = document.createElement('div');
  685. modal.classList.add('modal', 'fade');
  686. modal.innerHTML = `
  687. <div class="modal-dialog">
  688. <div class="modal-content">
  689. <div class="modal-header">
  690. <h5 class="modal-title">Crear Snapshot - ${vmName}</h5>
  691. <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
  692. </div>
  693. <div class="modal-body">
  694. <div class="mb-3">
  695. <label for="snapshotName" class="form-label">Nombre del Snapshot</label>
  696. <input type="text" class="form-control" id="snapshotName" placeholder="ej: snapshot-2026-01-18" required>
  697. </div>
  698. <div class="mb-3">
  699. <label for="snapshotDesc" class="form-label">Descripción (opcional)</label>
  700. <textarea class="form-control" id="snapshotDesc" rows="3" placeholder="Describe el propósito de este snapshot"></textarea>
  701. </div>
  702. </div>
  703. <div class="modal-footer">
  704. <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
  705. <button type="button" class="btn btn-warning" onclick="createSnapshot('${vmName}')">
  706. <i class="bi bi-camera"></i> Crear Snapshot
  707. </button>
  708. </div>
  709. </div>
  710. </div>
  711. `;
  712. document.body.appendChild(modal);
  713. const bsModal = new bootstrap.Modal(modal);
  714. bsModal.show();
  715. // Limpiar modal al cerrarlo
  716. modal.addEventListener('hidden.bs.modal', () => {
  717. modal.remove();
  718. });
  719. }
  720. // Create snapshot
  721. async function createSnapshot(vmName) {
  722. const snapshotName = document.getElementById('snapshotName').value.trim();
  723. const snapshotDesc = document.getElementById('snapshotDesc').value.trim();
  724. if (!snapshotName) {
  725. alert('El nombre del snapshot es obligatorio');
  726. return;
  727. }
  728. // Validar que el nombre sea válido (sin espacios ni caracteres especiales)
  729. if (!/^[a-zA-Z0-9._-]+$/.test(snapshotName)) {
  730. alert('El nombre del snapshot solo puede contener letras, números, puntos, guiones y guiones bajos');
  731. return;
  732. }
  733. try {
  734. const url = new URL(`${API_BASE}/vms/${vmName}/snapshot`);
  735. url.searchParams.append('snapshot_name', snapshotName);
  736. if (snapshotDesc) {
  737. url.searchParams.append('description', snapshotDesc);
  738. }
  739. const response = await fetch(url, { method: 'POST' });
  740. const data = await response.json();
  741. if (data.error) {
  742. alert(`Error: ${data.error}`);
  743. return;
  744. }
  745. alert(`✓ Snapshot "${snapshotName}" creado exitosamente`);
  746. // Cerrar modal - buscar el modal visible
  747. const visibleModal = document.querySelector('.modal.show');
  748. if (visibleModal) {
  749. const modalInstance = bootstrap.Modal.getInstance(visibleModal);
  750. if (modalInstance) {
  751. modalInstance.hide();
  752. }
  753. }
  754. } catch (error) {
  755. console.error('Error:', error);
  756. alert(`Error al crear snapshot: ${error.message}`);
  757. }
  758. }
  759. // Open snapshots list modal
  760. function openSnapshotsListModal(vmName) {
  761. const modal = document.createElement('div');
  762. modal.classList.add('modal', 'fade');
  763. modal.innerHTML = `
  764. <div class="modal-dialog modal-lg">
  765. <div class="modal-content">
  766. <div class="modal-header">
  767. <h5 class="modal-title">Snapshots - ${vmName}</h5>
  768. <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
  769. </div>
  770. <div class="modal-body">
  771. <div id="snapshotsList" class="text-center">
  772. <p class="text-muted">Cargando snapshots...</p>
  773. </div>
  774. </div>
  775. <div class="modal-footer">
  776. <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button>
  777. </div>
  778. </div>
  779. </div>
  780. `;
  781. document.body.appendChild(modal);
  782. const bsModal = new bootstrap.Modal(modal);
  783. bsModal.show();
  784. // Limpiar modal al cerrarlo
  785. modal.addEventListener('hidden.bs.modal', () => {
  786. modal.remove();
  787. });
  788. // Cargar snapshots
  789. loadSnapshotsList(vmName);
  790. }
  791. // Load and display snapshots list
  792. async function loadSnapshotsList(vmName) {
  793. try {
  794. const response = await fetch(`${API_BASE}/vms/${vmName}/snapshots`);
  795. const data = await response.json();
  796. if (data.error) {
  797. document.getElementById('snapshotsList').innerHTML = `<p class="text-danger">Error: ${data.error}</p>`;
  798. return;
  799. }
  800. const snapshots = data.snapshots;
  801. if (!snapshots || snapshots.length === 0) {
  802. document.getElementById('snapshotsList').innerHTML = '<p class="text-muted">No hay snapshots disponibles</p>';
  803. return;
  804. }
  805. let html = `
  806. <div class="table-responsive">
  807. <table class="table table-sm table-hover">
  808. <thead>
  809. <tr>
  810. <th>Nombre</th>
  811. <th>Creado</th>
  812. <th>Descripción</th>
  813. <th>Estado</th>
  814. <th>Acciones</th>
  815. </tr>
  816. </thead>
  817. <tbody>
  818. `;
  819. snapshots.forEach(snap => {
  820. let created = 'Desconocida';
  821. if (snap.created && snap.created > 0) {
  822. created = new Date(snap.created * 1000).toLocaleString('es-ES');
  823. }
  824. html += `
  825. <tr>
  826. <td><strong>${snap.name}</strong></td>
  827. <td>${created}</td>
  828. <td>${snap.description || '-'}</td>
  829. <td><span class="badge bg-info">${snap.state}</span></td>
  830. <td>
  831. <button class="btn btn-sm btn-danger" onclick="deleteSnapshotConfirm('${vmName}', '${snap.name}')">
  832. <i class="bi bi-trash"></i> Eliminar
  833. </button>
  834. </td>
  835. </tr>
  836. `;
  837. });
  838. html += `
  839. </tbody>
  840. </table>
  841. </div>
  842. `;
  843. document.getElementById('snapshotsList').innerHTML = html;
  844. } catch (error) {
  845. console.error('Error:', error);
  846. document.getElementById('snapshotsList').innerHTML = `<p class="text-danger">Error: ${error.message}</p>`;
  847. }
  848. }
  849. // Delete snapshot with confirmation
  850. function deleteSnapshotConfirm(vmName, snapshotName) {
  851. if (confirm(`¿Estás seguro de que deseas eliminar el snapshot "${snapshotName}"?`)) {
  852. deleteSnapshot(vmName, snapshotName);
  853. }
  854. }
  855. // Delete snapshot
  856. async function deleteSnapshot(vmName, snapshotName) {
  857. try {
  858. const encodedSnapshotName = encodeURIComponent(snapshotName);
  859. const response = await fetch(`${API_BASE}/vms/${vmName}/snapshots/${encodedSnapshotName}`, {
  860. method: 'DELETE'
  861. });
  862. const data = await response.json();
  863. if (data.error) {
  864. alert(`Error: ${data.error}`);
  865. return;
  866. }
  867. alert(`✓ Snapshot "${snapshotName}" eliminado exitosamente`);
  868. // Recargar lista de snapshots
  869. loadSnapshotsList(vmName);
  870. } catch (error) {
  871. console.error('Error:', error);
  872. alert(`Error al eliminar snapshot: ${error.message}`);
  873. }
  874. }
  875. // Chart instances storage
  876. let cpuChart = null;
  877. let memoryChart = null;
  878. let statsInterval = null;
  879. const statsHistory = {
  880. cpu: [],
  881. memory: [],
  882. maxPoints: 20
  883. };
  884. // Initialize and update performance charts
  885. async function initializePerformanceCharts(vmName) {
  886. // Clear any existing interval
  887. if (statsInterval) clearInterval(statsInterval);
  888. // Initialize charts immediately
  889. await updatePerformanceStats(vmName);
  890. // Update every 2 seconds
  891. statsInterval = setInterval(() => updatePerformanceStats(vmName), 2000);
  892. }
  893. // Update performance statistics
  894. async function updatePerformanceStats(vmName) {
  895. try {
  896. const response = await fetch(`${API_BASE}/vms/${vmName}/stats`);
  897. const data = await response.json();
  898. if (data.error || data.state === 'error') {
  899. console.log('VM not running or stats not available');
  900. return;
  901. }
  902. const timestamp = new Date().toLocaleTimeString('es-ES', {
  903. hour: '2-digit',
  904. minute: '2-digit',
  905. second: '2-digit'
  906. });
  907. // Update history
  908. statsHistory.cpu.push({
  909. time: timestamp,
  910. value: data.cpu_percent
  911. });
  912. statsHistory.memory.push({
  913. time: timestamp,
  914. value: data.memory_percent
  915. });
  916. // Keep only last maxPoints
  917. if (statsHistory.cpu.length > statsHistory.maxPoints) {
  918. statsHistory.cpu.shift();
  919. statsHistory.memory.shift();
  920. }
  921. // Update CPU Chart
  922. if (cpuChart) {
  923. cpuChart.data.labels = statsHistory.cpu.map(s => s.time);
  924. cpuChart.data.datasets[0].data = statsHistory.cpu.map(s => s.value);
  925. cpuChart.update('none');
  926. } else {
  927. createCPUChart();
  928. }
  929. // Update Memory Chart
  930. if (memoryChart) {
  931. memoryChart.data.labels = statsHistory.memory.map(s => s.time);
  932. memoryChart.data.datasets[0].data = statsHistory.memory.map(s => s.value);
  933. memoryChart.update('none');
  934. } else {
  935. createMemoryChart();
  936. }
  937. } catch (error) {
  938. console.error('Error updating stats:', error);
  939. }
  940. }
  941. // Create CPU chart
  942. function createCPUChart() {
  943. const ctx = document.getElementById('cpuChart');
  944. if (!ctx) return;
  945. // Destroy existing chart if any
  946. if (cpuChart) cpuChart.destroy();
  947. cpuChart = new Chart(ctx, {
  948. type: 'line',
  949. data: {
  950. labels: statsHistory.cpu.map(s => s.time),
  951. datasets: [{
  952. label: 'CPU (%)',
  953. data: statsHistory.cpu.map(s => s.value),
  954. borderColor: '#667eea',
  955. backgroundColor: 'rgba(102, 126, 234, 0.1)',
  956. tension: 0.4,
  957. fill: true,
  958. borderWidth: 2,
  959. pointRadius: 4,
  960. pointBackgroundColor: '#667eea',
  961. pointBorderColor: '#fff',
  962. pointBorderWidth: 2,
  963. pointHoverRadius: 6
  964. }],
  965. },
  966. options: {
  967. responsive: true,
  968. maintainAspectRatio: false,
  969. plugins: {
  970. legend: {
  971. display: true,
  972. labels: {
  973. font: { size: 12 },
  974. padding: 15,
  975. color: '#666'
  976. }
  977. },
  978. tooltip: {
  979. backgroundColor: 'rgba(0,0,0,0.8)',
  980. padding: 12,
  981. titleFont: { size: 12 },
  982. bodyFont: { size: 12 },
  983. callbacks: {
  984. label: function(context) {
  985. return context.dataset.label + ': ' + context.parsed.y.toFixed(2) + '%';
  986. }
  987. }
  988. }
  989. },
  990. scales: {
  991. y: {
  992. beginAtZero: true,
  993. max: 100,
  994. ticks: {
  995. stepSize: 25,
  996. callback: function(value) {
  997. return value + '%';
  998. }
  999. },
  1000. grid: {
  1001. color: 'rgba(0,0,0,0.05)'
  1002. }
  1003. },
  1004. x: {
  1005. grid: {
  1006. color: 'rgba(0,0,0,0.05)'
  1007. }
  1008. }
  1009. }
  1010. }
  1011. });
  1012. }
  1013. // Create Memory chart
  1014. function createMemoryChart() {
  1015. const ctx = document.getElementById('memoryChart');
  1016. if (!ctx) return;
  1017. // Destroy existing chart if any
  1018. if (memoryChart) memoryChart.destroy();
  1019. memoryChart = new Chart(ctx, {
  1020. type: 'line',
  1021. data: {
  1022. labels: statsHistory.memory.map(s => s.time),
  1023. datasets: [{
  1024. label: 'Memoria (%)',
  1025. data: statsHistory.memory.map(s => s.value),
  1026. borderColor: '#764ba2',
  1027. backgroundColor: 'rgba(118, 75, 162, 0.1)',
  1028. tension: 0.4,
  1029. fill: true,
  1030. borderWidth: 2,
  1031. pointRadius: 4,
  1032. pointBackgroundColor: '#764ba2',
  1033. pointBorderColor: '#fff',
  1034. pointBorderWidth: 2,
  1035. pointHoverRadius: 6
  1036. }],
  1037. },
  1038. options: {
  1039. responsive: true,
  1040. maintainAspectRatio: false,
  1041. plugins: {
  1042. legend: {
  1043. display: true,
  1044. labels: {
  1045. font: { size: 12 },
  1046. padding: 15,
  1047. color: '#666'
  1048. }
  1049. },
  1050. tooltip: {
  1051. backgroundColor: 'rgba(0,0,0,0.8)',
  1052. padding: 12,
  1053. titleFont: { size: 12 },
  1054. bodyFont: { size: 12 },
  1055. callbacks: {
  1056. label: function(context) {
  1057. return context.dataset.label + ': ' + context.parsed.y.toFixed(2) + '%';
  1058. }
  1059. }
  1060. }
  1061. },
  1062. scales: {
  1063. y: {
  1064. beginAtZero: true,
  1065. max: 100,
  1066. ticks: {
  1067. stepSize: 25,
  1068. callback: function(value) {
  1069. return value + '%';
  1070. }
  1071. },
  1072. grid: {
  1073. color: 'rgba(0,0,0,0.05)'
  1074. }
  1075. },
  1076. x: {
  1077. grid: {
  1078. color: 'rgba(0,0,0,0.05)'
  1079. }
  1080. }
  1081. }
  1082. }
  1083. });
  1084. }
  1085. // Clean up charts when switching VMs
  1086. function cleanupCharts() {
  1087. if (statsInterval) {
  1088. clearInterval(statsInterval);
  1089. statsInterval = null;
  1090. }
  1091. if (cpuChart) {
  1092. cpuChart.destroy();
  1093. cpuChart = null;
  1094. }
  1095. if (memoryChart) {
  1096. memoryChart.destroy();
  1097. memoryChart = null;
  1098. }
  1099. // Reset history
  1100. statsHistory.cpu = [];
  1101. statsHistory.memory = [];
  1102. }