From 4227e84fdca44c9fbeac058d31a52c4e6e3ddd85 Mon Sep 17 00:00:00 2001 From: Ari <149393150+A21-devs@users.noreply.github.com> Date: Sat, 5 Dec 2026 15:12:07 -0500 Subject: [PATCH 1/3] Linked clone: leave a marker, and put a cut-off clone right at startup A linked clone moves the source's disk to the shared base before it makes the two overlays. If the app stops in between, the source VM points at a disk that isn't there, and its next Power on makes a blank one while the real data sits in the .base file. The clone now writes .vmm-linking in the disks folder first, naming the source disk, the base and the new overlay, and removes it once the new VM's config is saved. To get that order, cloneVm takes the save as a callback instead of the IPC handler saving after it returns. At startup, recoverLinkedClones reads each marker. With the source disk missing it moves the base back. With the source overlay in place the clone is usable, so it makes the base read-only like a finished clone and removes the new overlay if no VM was saved with it. A marker it can't act on yet (base in use) stays for the next start. --- src/main/disks.ts | 95 +++++++++++++++++++++++++++++++++++++++++++---- src/main/ipc.ts | 8 ++-- 2 files changed, 93 insertions(+), 10 deletions(-) diff --git a/src/main/disks.ts b/src/main/disks.ts index 0bdebc3..2d0b6bc 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,59 @@ 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: 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 { + 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 +199,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 +209,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 +223,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,7 +243,15 @@ 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 { + renameSync(cfg.diskPath, base) + } catch (e) { + tryRemove(marker) + throw e + } try { await img.createOverlay(cfg.diskPath, base) await img.createOverlay(target, base) @@ -184,16 +261,20 @@ export async function cloneVm( 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)) }) }) From cb01e0d1615cf09d4deb42814339b4afe9e57c2b Mon Sep 17 00:00:00 2001 From: Ari <149393150+A21-devs@users.noreply.github.com> Date: Sat, 5 Dec 2026 15:12:58 -0500 Subject: [PATCH 2/3] Test a linked clone cut off before and after its overlays Uses a fake qemu-img that never finishes, the way a quit leaves it, and checks what the next start puts right. The Still working question can now say a cut-off clone of either kind is undone at the next start. --- src/main/quitFlow.ts | 2 +- tests/clones.test.ts | 92 +++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 91 insertions(+), 3 deletions(-) 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..0293ede 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,89 @@ 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) 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('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([]) + }) +}) From 1c2d9d06498e60dcc92cf312ad9dd3d376bda60c Mon Sep 17 00:00:00 2001 From: Ari <149393150+A21-devs@users.noreply.github.com> Date: Sat, 5 Dec 2026 15:15:43 -0500 Subject: [PATCH 3/3] Linked clone: write each overlay under a temporary name qemu-img create writes the overlay in place, so a quit while it runs can leave half a qcow2 at the source's disk path, which the startup recovery would take for a finished overlay and keep. Each overlay is now created as .vmm-clone and renamed into place, and the recovery removes any temporary overlay a marker names. --- src/main/disks.ts | 24 ++++++++++++++++++------ tests/clones.test.ts | 30 +++++++++++++++++++++++++++++- 2 files changed, 47 insertions(+), 7 deletions(-) diff --git a/src/main/disks.ts b/src/main/disks.ts index 2d0b6bc..b97bb74 100644 --- a/src/main/disks.ts +++ b/src/main/disks.ts @@ -83,8 +83,9 @@ export function removeUnfinishedCompacts(configs: VmConfig[]): string[] { * 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: 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 + * - 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. */ @@ -106,6 +107,8 @@ export function recoverLinkedClones(disksDir: string, library: VmConfig[]): stri 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) @@ -252,12 +255,21 @@ export async function cloneVm( 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 img.createOverlay(cfg.diskPath, base) - await img.createOverlay(target, base) + await overlay(cfg.diskPath) + await overlay(target) } catch (e) { - tryRemove(target) - tryRemove(cfg.diskPath) + for (const f of [target, cfg.diskPath]) { + tryRemove(`${f}${CLONE_SUFFIX}`) + tryRemove(f) + } try { renameSync(base, cfg.diskPath) // put the original back } catch { diff --git a/tests/clones.test.ts b/tests/clones.test.ts index 0293ede..11f091d 100644 --- a/tests/clones.test.ts +++ b/tests/clones.test.ts @@ -117,7 +117,10 @@ describe('linked clone cut off mid-way', () => { createOverlay: (file: string) => { made++ // the app going away mid-clone: the promise never settles and nothing after it runs - if (made === o.hangOn) return new Promise(() => undefined) + 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() } @@ -143,6 +146,31 @@ describe('linked clone cut off mid-way', () => { 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)