diff --git a/src/main/disks.ts b/src/main/disks.ts index 0bdebc3..b97bb74 100644 --- a/src/main/disks.ts +++ b/src/main/disks.ts @@ -1,5 +1,5 @@ -import { chmodSync, existsSync, readdirSync, renameSync, rmSync } from 'node:fs' -import { join } from 'node:path' +import { chmodSync, existsSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs' +import { basename, join, resolve } from 'node:path' import { validateVmName, type PortForward, type VmConfig } from '@shared/config' import type { DataPaths } from './paths' import type { ImgSnapshot } from './qemuImg' @@ -14,6 +14,18 @@ const GB = 1024 ** 3 */ export const CLONE_SUFFIX = '.vmm-clone' export const COMPACT_SUFFIX = '.compact.tmp' +/** a linked clone being set up, see recoverLinkedClones */ +export const LINK_SUFFIX = '.vmm-linking' + +/** What a linked clone writes down before it moves the source's disk out of the way. */ +interface LinkMarker { + /** the source VM's disk, which becomes an overlay */ + diskPath: string + /** where the source's disk was moved to, the shared base */ + base: string + /** the new VM's overlay */ + target: string +} /** * Deletes the clone and compact files the app was writing when it last stopped, so a Quit @@ -64,6 +76,62 @@ export function removeUnfinishedCompacts(configs: VmConfig[]): string[] { return removed } +/** + * Finishes or undoes linked clones the app was stopped in the middle of. A linked clone moves + * the source's disk to the base before it creates the overlays, and cut off in between, the + * source VM points at a disk that isn't there: its next Power on would make a blank one. Each + * clone leaves a marker in the disks folder until it is done, so this knows which base is whose. + * + * - source disk missing: move the base back, the clone never happened + * - source overlay there (always a whole one, it is renamed into place): the source works on top + * of the base, so make the base read-only like a finished clone does, and drop the new VM's + * overlay if no VM got saved with it + * + * Call it at startup before any VM can start. Returns what it did, for the log. + */ +export function recoverLinkedClones(disksDir: string, library: VmConfig[]): string[] { + let names: string[] + try { + names = readdirSync(disksDir).filter((f) => f.toLowerCase().endsWith(LINK_SUFFIX)) + } catch { + return [] // folder missing + } + const done: string[] = [] + for (const f of names) { + const file = join(disksDir, f) + let m: LinkMarker + try { + m = JSON.parse(readFileSync(file, 'utf8')) as LinkMarker + if (typeof m.diskPath !== 'string' || typeof m.base !== 'string' || typeof m.target !== 'string') throw new Error('bad marker') + } catch { + continue // not one we can read: leave it rather than guess + } + try { + // half-written overlays, see cloneVm. The disks folder scan gets the new VM's, not the source's + for (const f of [m.diskPath, m.target]) tryRemove(`${f}${CLONE_SUFFIX}`) + if (!existsSync(m.diskPath)) { + if (existsSync(m.base)) { + renameSync(m.base, m.diskPath) + done.push(`moved ${m.base} back to ${m.diskPath}`) + } + tryRemove(m.target) // an overlay is only made after the source's, so this is a no-op + } else { + if (existsSync(m.base)) chmodSync(m.base, 0o444) + // Windows paths ignore case, and a config may spell the folder differently + const same = (p: string) => resolve(p).toLowerCase() === resolve(m.target).toLowerCase() + if (existsSync(m.target) && !library.some((c) => same(c.diskPath))) { + tryRemove(m.target) + done.push(`removed ${m.target}, a linked clone that was never saved`) + } + } + rmSync(file) + } catch { + // the base is in use or can't be moved: keep the marker and try again at the next start + } + } + return done +} + function needOff(runner: VmRunner, cfg: VmConfig, what: string): void { if (runner.isRunning(cfg.name)) throw new Error(`Power off ${cfg.name} before you ${what}.`) } @@ -134,7 +202,9 @@ export function shiftForwards(forwards: PortForward[], others: VmConfig[]): Port * Full clone: an independent copy of the disk. * Linked clone: both VMs become thin overlays on a shared read-only base, so the copy * takes seconds and almost no space. The source's current disk turns into that base. - * `library` is every VM, the source included. + * `library` is every VM, the source included. `save` stores the new VM's config and returns it + * as stored; it runs before a linked clone's marker is removed, so a stop in between still gets + * the unused overlay cleaned up. */ export async function cloneVm( runner: VmRunner, @@ -142,7 +212,8 @@ export async function cloneVm( cfg: VmConfig, newName: string, linked: boolean, - library: VmConfig[] + library: VmConfig[], + save: (copy: VmConfig) => VmConfig = (c) => c ): Promise { const name = newName.trim() const err = validateVmName(name) @@ -155,6 +226,7 @@ export async function cloneVm( if (existsSync(target)) throw new Error(`${target} already exists`) const img = runner.img() + let marker: string | null = null if (!linked) { // 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 @@ -174,26 +246,47 @@ export async function cloneVm( throw new Error(`A linked clone freezes the current disk as a shared base, and this VM's ${what} would be stuck inside it. Delete them first, or make a full clone.`) } const base = cfg.diskPath.replace(/\.qcow2$/i, '') + `.base-${Date.now().toString(36)}.qcow2` - renameSync(cfg.diskPath, base) + // written first, so a clone the app is stopped in the middle of can be put right at the next start + marker = join(paths.disks, `${basename(base)}${LINK_SUFFIX}`) + writeFileSync(marker, JSON.stringify({ diskPath: cfg.diskPath, base, target } satisfies LinkMarker)) try { - await img.createOverlay(cfg.diskPath, base) - await img.createOverlay(target, base) + renameSync(cfg.diskPath, base) } catch (e) { - tryRemove(target) - tryRemove(cfg.diskPath) + tryRemove(marker) + throw e + } + // each overlay is written under a temporary name and renamed into place, so a file at either + // path is always a whole overlay. qemu-img killed mid-write would otherwise leave half of one + // where recoverLinkedClones takes it for finished. The overlay stores the base's path, not its own + const overlay = async (file: string) => { + await img.createOverlay(`${file}${CLONE_SUFFIX}`, base) + renameSync(`${file}${CLONE_SUFFIX}`, file) + } + try { + await overlay(cfg.diskPath) + await overlay(target) + } catch (e) { + for (const f of [target, cfg.diskPath]) { + tryRemove(`${f}${CLONE_SUFFIX}`) + tryRemove(f) + } 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 + // the overlay is still in the way: say where the disk went rather than hide it. The marker + // stays, so the next start tries the move again 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}.`) } + tryRemove(marker) throw e } // the base must never change again or both overlays break chmodSync(base, 0o444) } - return { ...cfg, name, diskPath: target, forwards: shiftForwards(cfg.forwards, library), autostart: false, resumeLast: false } + const saved = save({ ...cfg, name, diskPath: target, forwards: shiftForwards(cfg.forwards, library), autostart: false, resumeLast: false }) + if (marker) tryRemove(marker) + return saved } diff --git a/src/main/ipc.ts b/src/main/ipc.ts index 98eb764..2cba940 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, removeUnfinishedCompacts, removeUnfinishedDisks, resizeDisk } from './disks' +import { cloneVm, compactDisk, recoverLinkedClones, removeUnfinishedCompacts, removeUnfinishedDisks, resizeDisk } from './disks' import { runAutostart } from './autostart' import { GuestSetupServer } from './guestSetup' import { importIso, listIsos, removeUnfinishedCopies, watchFolder } from './isos' @@ -68,6 +68,9 @@ export function registerIpc(ctx: IpcContext): Backend { // 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), ...removeUnfinishedCompacts(listConfigs(paths))] if (halfDisks.length) console.log(`removed unfinished disk files: ${halfDisks.join(', ')}`) + // and a linked clone stopped between moving the source's disk and making the overlays + const relinked = recoverLinkedClones(paths.disks, listConfigs(paths)) + if (relinked.length) console.log(`put right unfinished linked clones: ${relinked.join('; ')}`) // new or removed ISOs show up without restarting the app const stopIsoWatch = watchFolder(paths.isos, () => send('host:changed')) @@ -179,8 +182,7 @@ export function registerIpc(ctx: IpcContext): Backend { ipcMain.handle('clone', async (_e, name: string, newName: unknown, linked: unknown) => { if (typeof newName !== 'string') throw new Error('Name is required') return withDiskWork(name, 'cloning', async () => { - const copy = await cloneVm(runner, paths, byName(name), newName, linked === true, listConfigs(paths)) - return saveConfig(paths, copy) + return cloneVm(runner, paths, byName(name), newName, linked === true, listConfigs(paths), (copy) => saveConfig(paths, copy)) }) }) diff --git a/src/main/quitFlow.ts b/src/main/quitFlow.ts index 231ce6b..d43cc04 100644 --- a/src/main/quitFlow.ts +++ b/src/main/quitFlow.ts @@ -63,7 +63,7 @@ const cutOff: Record = { saving: 'no profile is made and the VM is not started again', launching: 'the VM may be rolled back to the profile without being started', removing: 'the profile may not be deleted', - cloning: 'an unfinished full copy of the disk is deleted the next time the app starts, but a linked clone cut off while it sets up can leave the VM without its disk', + cloning: 'the unfinished clone is undone the next time the app starts', compacting: 'the unfinished compacted copy is deleted the next time the app starts', growing: 'the disk may not get its new size' } diff --git a/tests/clones.test.ts b/tests/clones.test.ts index 65917dc..11f091d 100644 --- a/tests/clones.test.ts +++ b/tests/clones.test.ts @@ -1,9 +1,11 @@ -import { mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { existsSync, mkdtempSync, readdirSync, rmSync, statSync, 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 { CLONE_SUFFIX, COMPACT_SUFFIX, removeUnfinishedCompacts, removeUnfinishedDisks, shiftForwards } from '../src/main/disks' +import { CLONE_SUFFIX, COMPACT_SUFFIX, LINK_SUFFIX, cloneVm, recoverLinkedClones, removeUnfinishedCompacts, removeUnfinishedDisks, shiftForwards } from '../src/main/disks' +import { dataPaths } from '../src/main/paths' +import type { VmRunner } from '../src/main/vmRunner' import { suggestCloneName } from '../src/renderer/src/components/CloneDialog' const withFwd = (name: string, forwards: PortForward[]) => ({ ...defaultConfig(name, 'C:\\VMs\\disks'), forwards }) @@ -99,3 +101,117 @@ describe('removeUnfinishedCompacts', () => { expect(removeUnfinishedCompacts([cfg])).toEqual([]) }) }) + +describe('linked clone cut off mid-way', () => { + let root: string + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'vmm-link-')) + }) + afterEach(() => rmSync(root, { recursive: true, force: true })) + + /** a runner whose qemu-img makes overlays as plain files, or never finishes the second one */ + function fakeRunner(o: { hangOn?: number } = {}): VmRunner { + let made = 0 + const img = { + info: async () => ({ snapshots: [], virtualBytes: 0, actualBytes: 0, backingFile: null }), + createOverlay: (file: string) => { + made++ + // the app going away mid-clone: the promise never settles and nothing after it runs + if (made === o.hangOn) { + writeFileSync(file, 'half an overlay') // what a killed qemu-img leaves behind + return new Promise(() => undefined) + } + writeFileSync(file, 'overlay') + return Promise.resolve() + } + } + return { isRunning: () => false, img: () => img } as unknown as VmRunner + } + + const markers = (dir: string) => readdirSync(dir).filter((f) => f.endsWith(LINK_SUFFIX)) + const settle = () => new Promise((r) => setTimeout(r, 0)) + + it('moves the disk back when the app stopped before the overlays', async () => { + const paths = dataPaths(root) + const src = defaultConfig('Kali', paths.disks) + writeFileSync(src.diskPath, 'the real disk') + void cloneVm(fakeRunner({ hangOn: 1 }), paths, src, 'Kali copy', true, [src]) + await settle() + // where the app stopped: the source's disk is gone, the base and the marker are there + expect(existsSync(src.diskPath)).toBe(false) + expect(markers(paths.disks)).toHaveLength(1) + const done = recoverLinkedClones(paths.disks, [src]) + expect(done[0]).toMatch(/^moved .*\.base-.*\.qcow2 back to /) + expect(existsSync(src.diskPath)).toBe(true) + expect(readdirSync(paths.disks)).toEqual(['Kali.qcow2']) + }) + + it('never takes a half-written source overlay for a finished one', async () => { + const paths = dataPaths(root) + const src = defaultConfig('Kali', paths.disks) + writeFileSync(src.diskPath, 'the real disk') + void cloneVm(fakeRunner({ hangOn: 1 }), paths, src, 'Kali copy', true, [src]) + await settle() + // qemu-img was in the middle of the source's overlay: it is under its temporary name + expect(existsSync(`${src.diskPath}${CLONE_SUFFIX}`)).toBe(true) + expect(existsSync(src.diskPath)).toBe(false) + recoverLinkedClones(paths.disks, [src]) + expect(readdirSync(paths.disks)).toEqual(['Kali.qcow2']) + }) + + it('drops a half-written new overlay too', async () => { + const paths = dataPaths(root) + const src = defaultConfig('Kali', paths.disks) + writeFileSync(src.diskPath, 'the real disk') + void cloneVm(fakeRunner({ hangOn: 2 }), paths, src, 'Kali copy', true, [src]) + await settle() + expect(existsSync(join(paths.disks, `Kali copy.qcow2${CLONE_SUFFIX}`))).toBe(true) + recoverLinkedClones(paths.disks, [src]) + const base = readdirSync(paths.disks).find((f) => f.includes('.base-'))! + expect(readdirSync(paths.disks).sort()).toEqual([base, 'Kali.qcow2'].sort()) + }) + + it('keeps a source overlay, locks the base and drops the unsaved new overlay', async () => { + const paths = dataPaths(root) + const src = defaultConfig('Kali', paths.disks) + writeFileSync(src.diskPath, 'the real disk') + // both overlays made, then the app stopped before the new VM's config was saved + await expect( + cloneVm(fakeRunner(), paths, src, 'Kali copy', true, [src], () => { + throw new Error('stopped here') + }) + ).rejects.toThrow('stopped here') + expect(existsSync(join(paths.disks, 'Kali copy.qcow2'))).toBe(true) + expect(markers(paths.disks)).toHaveLength(1) + const done = recoverLinkedClones(paths.disks, [src]) + expect(done).toEqual([`removed ${join(paths.disks, 'Kali copy.qcow2')}, a linked clone that was never saved`]) + const base = readdirSync(paths.disks).find((f) => f.includes('.base-'))! + expect(readdirSync(paths.disks).sort()).toEqual([base, 'Kali.qcow2'].sort()) + // read-only, like a finished clone leaves it + expect(statSync(join(paths.disks, base)).mode & 0o200).toBe(0) + }) + + it('leaves a clone whose config was saved alone, and removes its marker once saved', async () => { + const paths = dataPaths(root) + const src = defaultConfig('Kali', paths.disks) + writeFileSync(src.diskPath, 'the real disk') + let markerAtSave = 0 + const copy = await cloneVm(fakeRunner(), paths, src, 'Kali copy', true, [src], (c) => { + markerAtSave = markers(paths.disks).length + return c + }) + // the marker is still there while the config is saved, and gone after + expect(markerAtSave).toBe(1) + expect(markers(paths.disks)).toEqual([]) + expect(recoverLinkedClones(paths.disks, [src, copy])).toEqual([]) + expect(existsSync(copy.diskPath)).toBe(true) + }) + + it('leaves a marker it cannot read and copes with a missing folder', () => { + const paths = dataPaths(root) + writeFileSync(join(paths.disks, `x.base-1.qcow2${LINK_SUFFIX}`), 'not json') + expect(recoverLinkedClones(paths.disks, [])).toEqual([]) + expect(markers(paths.disks)).toHaveLength(1) + expect(recoverLinkedClones(join(root, 'nope'), [])).toEqual([]) + }) +})