diff --git a/src/main/disks.ts b/src/main/disks.ts index 91fdd4a..dc8b0c5 100644 --- a/src/main/disks.ts +++ b/src/main/disks.ts @@ -1,4 +1,4 @@ -import { chmodSync, existsSync, renameSync, rmSync } from 'node:fs' +import { chmodSync, existsSync, readdirSync, renameSync, rmSync } from 'node:fs' import { join } from 'node:path' import { validateVmName, type PortForward, type VmConfig } from '@shared/config' import type { DataPaths } from './paths' @@ -7,10 +7,54 @@ import { QUICKSAVE, type VmRunner } from './vmRunner' const GB = 1024 ** 3 +/** + * Suffixes of a disk this app is in the middle of writing. Neither is .part on purpose: a + * browser downloading a disk image into the disks folder writes .qcow2.part, and the + * startup cleanup must never touch another program's file. + */ +export const CLONE_SUFFIX = '.vmm-clone' +export const COMPACT_SUFFIX = '.compact.tmp' + +/** + * Deletes the clone and compact files the app was writing when it last stopped, so a Quit + * anyway in the middle of either doesn't leave a big file behind for good. Returns their names. + * + * Only files it knows it wrote: a disk in here with no VM may well be one the user kept on + * purpose, because deleting a VM leaves its disk. A disk the config points at outside this + * folder keeps its leftover until the next compact of that VM replaces it. + */ +export function removeUnfinishedDisks(disksDir: string): string[] { + let names: string[] + try { + names = readdirSync(disksDir) + } catch { + return [] // folder missing + } + return names.filter((f) => { + const l = f.toLowerCase() + if (!l.endsWith(`.qcow2${CLONE_SUFFIX}`) && !l.endsWith(`.qcow2${COMPACT_SUFFIX}`)) return false + try { + rmSync(join(disksDir, f)) + return true + } catch { + return false // in use or no permission: the next compact or clone overwrites it + } + }) +} + function needOff(runner: VmRunner, cfg: VmConfig, what: string): void { if (runner.isRunning(cfg.name)) throw new Error(`Power off ${cfg.name} before you ${what}.`) } +/** tidy-up after a failure must never replace the error that caused it */ +function tryRemove(path: string): void { + try { + rmSync(path, { force: true }) + } catch { + // in use or no permission: leave it, the startup cleanup or the next write deals with it + } +} + /** "save state" when the only snapshot is the quick save, "profiles" otherwise */ const snapshotWord = (snaps: ImgSnapshot[]) => (snaps.every((s) => s.name === QUICKSAVE) ? 'save state' : 'profiles') @@ -36,15 +80,15 @@ export async function compactDisk(runner: VmRunner, cfg: VmConfig): Promise<{ be // convert doesn't copy internal snapshots, they would be gone afterwards if (info.snapshots.length > 0) throw new Error(`Compacting would throw away this VM's ${snapshotWord(info.snapshots)}. Delete them first if you really want to.`) if (info.backingFile) throw new Error('This disk is a linked clone. Compacting it would copy the whole base disk into it.') - const tmp = `${cfg.diskPath}.compact.tmp` - rmSync(tmp, { force: true }) + const tmp = `${cfg.diskPath}${COMPACT_SUFFIX}` try { + // convert overwrites a leftover from a compact that was cut off await img.convert(cfg.diskPath, tmp) // one rename that replaces the disk. With two (disk -> .old, tmp -> disk) a crash in between // leaves no file at diskPath, and the next Power on would create a blank disk there renameSync(tmp, cfg.diskPath) } catch (e) { - rmSync(tmp, { force: true }) // the original is untouched + tryRemove(tmp) // the original is untouched throw e } return { before: info.actualBytes, after: (await img.info(cfg.diskPath)).actualBytes } @@ -90,11 +134,15 @@ export async function cloneVm( const img = runner.img() if (!linked) { - // convert doesn't copy internal snapshots, so the copy starts without the source's profiles + // written under a name no VM can use, so a copy the app is killed in the middle of is + // recognisable as ours and cleaned up at the next start instead of looking like a real disk + const part = `${target}${CLONE_SUFFIX}` try { - await img.convert(cfg.diskPath, target) + // convert overwrites a leftover from a clone that was cut off + await img.convert(cfg.diskPath, part) + renameSync(part, target) } catch (e) { - rmSync(target, { force: true }) // don't leave a half-written disk that blocks the next try + tryRemove(part) // don't leave a half-written disk that blocks the next try throw e } } else { @@ -109,9 +157,17 @@ export async function cloneVm( await img.createOverlay(cfg.diskPath, base) await img.createOverlay(target, base) } catch (e) { - rmSync(target, { force: true }) - rmSync(cfg.diskPath, { force: true }) - renameSync(base, cfg.diskPath) // put the original back + tryRemove(target) + tryRemove(cfg.diskPath) + try { + renameSync(base, cfg.diskPath) // put the original back + } catch { + // the overlay is still in the way: say where the disk went rather than hide it + const why = e instanceof Error ? e.message : String(e) + throw new Error(`${why} + +The original disk is at ${base}. Move it back to ${cfg.diskPath} before starting ${cfg.name}.`) + } throw e } // the base must never change again or both overlays break diff --git a/src/main/ipc.ts b/src/main/ipc.ts index 80b9427..05520d1 100644 --- a/src/main/ipc.ts +++ b/src/main/ipc.ts @@ -5,7 +5,7 @@ import { isAbsolute } from 'node:path' import { defaultConfig, validPort, type VmConfig } from '@shared/config' import { workText, type AppSettings, type AutostartIssue, type DiskInfo, type DiskWork, type HostInfo, type PowerAction, type Profile, type SaveStateResult, type StartResult, type VmWork, type VmWorkState } from '@shared/ipc' import { agentHibernate } from './agent' -import { cloneVm, compactDisk, resizeDisk } from './disks' +import { cloneVm, compactDisk, removeUnfinishedDisks, resizeDisk } from './disks' import { runAutostart } from './autostart' import { GuestSetupServer } from './guestSetup' import { importIso, listIsos, removeUnfinishedCopies, watchFolder } from './isos' @@ -65,6 +65,10 @@ export function registerIpc(ctx: IpcContext): Backend { const leftovers = removeUnfinishedCopies(paths.isos) if (leftovers.length) console.log(`removed unfinished ISO copies: ${leftovers.join(', ')}`) + // the same for a clone or a compact the app was quit in the middle of, which can be tens of GB + const halfDisks = removeUnfinishedDisks(paths.disks) + if (halfDisks.length) console.log(`removed unfinished disk files: ${halfDisks.join(', ')}`) + // new or removed ISOs show up without restarting the app const stopIsoWatch = watchFolder(paths.isos, () => send('host:changed')) diff --git a/tests/clones.test.ts b/tests/clones.test.ts index 319a79a..702617f 100644 --- a/tests/clones.test.ts +++ b/tests/clones.test.ts @@ -1,6 +1,9 @@ -import { describe, expect, it } from 'vitest' +import { mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { defaultConfig, type PortForward } from '@shared/config' -import { shiftForwards } from '../src/main/disks' +import { CLONE_SUFFIX, COMPACT_SUFFIX, removeUnfinishedDisks, shiftForwards } from '../src/main/disks' import { suggestCloneName } from '../src/renderer/src/components/CloneDialog' const withFwd = (name: string, forwards: PortForward[]) => ({ ...defaultConfig(name, 'C:\\VMs\\disks'), forwards }) @@ -39,3 +42,28 @@ describe('suggestCloneName', () => { expect(suggestCloneName('Kali', ['Kali', 'kali COPY', 'Kali copy 2'])).toBe('Kali copy 3') }) }) + +describe('removeUnfinishedDisks', () => { + let dir: string + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'vmm-disks-')) + }) + afterEach(() => rmSync(dir, { recursive: true, force: true })) + + it('deletes the clone and compact files it was writing and leaves everything else', () => { + writeFileSync(join(dir, 'Kali.qcow2'), 'disk') + writeFileSync(join(dir, 'Kali.base-m1.qcow2'), 'base of a linked clone') + writeFileSync(join(dir, `Kali copy.qcow2${CLONE_SUFFIX}`), 'half a clone') + writeFileSync(join(dir, `KALI.QCOW2${COMPACT_SUFFIX.toUpperCase()}`), 'half a compact') + // a browser downloading a disk image writes this, and it may be in progress right now + writeFileSync(join(dir, 'debian.qcow2.part'), 'downloading') + // a disk the user kept after deleting its VM: no config points at it, it still stays + writeFileSync(join(dir, 'old-parrot.qcow2'), 'kept on purpose') + expect(removeUnfinishedDisks(dir).sort()).toEqual([`KALI.QCOW2${COMPACT_SUFFIX.toUpperCase()}`, `Kali copy.qcow2${CLONE_SUFFIX}`]) + expect(readdirSync(dir).sort()).toEqual(['Kali.base-m1.qcow2', 'Kali.qcow2', 'debian.qcow2.part', 'old-parrot.qcow2']) + }) + + it('copes with a missing folder', () => { + expect(removeUnfinishedDisks(join(dir, 'nope'))).toEqual([]) + }) +}) diff --git a/tests/integration/clones.test.ts b/tests/integration/clones.test.ts index f7d637c..07e3476 100644 --- a/tests/integration/clones.test.ts +++ b/tests/integration/clones.test.ts @@ -6,7 +6,7 @@ import { join } from 'node:path' import { afterAll, describe, expect, it } from 'vitest' import { defaultConfig, type VmConfig } from '@shared/config' import type { VmRuntimeState } from '@shared/ipc' -import { cloneVm } from '../../src/main/disks' +import { CLONE_SUFFIX, cloneVm } from '../../src/main/disks' import { dataPaths, findQemu } from '../../src/main/paths' import { VmRunner } from '../../src/main/vmRunner' @@ -61,6 +61,8 @@ describe.skipIf(!qemu)('clones with real qemu-img', () => { const full = await cloneVm(runner, paths, src, 'clone full', false, [src, linked]) expect((await runner.img().info(full.diskPath)).backingFile).toBeNull() + // the copy is written under .vmm-clone and renamed, so nothing is left under that name + expect(existsSync(`${full.diskPath}${CLONE_SUFFIX}`)).toBe(false) // names are compared like Windows compares file names await expect(cloneVm(runner, paths, src, 'CLONE FULL', false, [src, linked, full])).rejects.toThrow(/already exists/)