Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/main/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { agentHibernate } from './agent'
import { cloneVm, compactDisk, resizeDisk } from './disks'
import { runAutostart } from './autostart'
import { GuestSetupServer } from './guestSetup'
import { importIso, listIsos, watchFolder } from './isos'
import { importIso, listIsos, removeUnfinishedCopies, watchFolder } from './isos'
import { detectAccel, findQemu, qemuVersion, type DataPaths } from './paths'
import { Profiles } from './profiles'
import { checkDataRoot, loadSettings, normalizeSettings, saveSettings } from './settings'
Expand Down Expand Up @@ -50,6 +50,11 @@ export function registerIpc(ctx: IpcContext): Backend {
runner.on('state', (s) => send('vm:state', s))
runner.on('crash', (c) => send('vm:crash', c))

// a copy the app was closed in the middle of. Nothing copies yet, the single instance lock
// keeps a second copy of the app from doing it either
const leftovers = removeUnfinishedCopies(paths.isos)
if (leftovers.length) console.log(`removed unfinished ISO copies: ${leftovers.join(', ')}`)

// new or removed ISOs show up without restarting the app
const stopIsoWatch = watchFolder(paths.isos, () => send('host:changed'))

Expand Down
33 changes: 31 additions & 2 deletions src/main/isos.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { existsSync, readdirSync, statSync, watch } from 'node:fs'
import { existsSync, readdirSync, rmSync, statSync, watch } from 'node:fs'
import { copyFile, rename, rm } from 'node:fs/promises'
import { basename, extname, join } from 'node:path'
import type { VmConfig } from '@shared/config'
Expand Down Expand Up @@ -42,12 +42,18 @@ export async function importIso(src: string, isosDir: string, mode: 'copy' | 're
return done
}

/**
* Suffix of a copy in progress. Not .part: Firefox downloads to <name>.iso.part, and the
* startup cleanup must never touch a download another program is writing.
*/
export const COPY_SUFFIX = '.vmm-copy'

/** copies running right now, by lowercased target path */
const copying = new Map<string, { src: string; done: Promise<string> }>()

async function copyInto(src: string, target: string): Promise<string> {
// copy under a name the ISO list ignores, so a half-copied file never shows up as bootable
const part = `${target}.part`
const part = `${target}${COPY_SUFFIX}`
try {
await copyFile(src, part)
await rename(part, target)
Expand All @@ -58,6 +64,29 @@ async function copyInto(src: string, target: string): Promise<string> {
return target
}

/**
* Deletes the files a copy the app didn't finish (closed or crashed mid-copy) left in the
* ISOs folder. Only ones with our own suffix, so other programs' downloads are safe. Only safe while no copy can be running, so call it once at startup.
* Returns the names it removed. A file that can't be deleted is skipped and tried next time.
*/
export function removeUnfinishedCopies(isosDir: string): string[] {
let names: string[]
try {
names = readdirSync(isosDir)
} catch {
return [] // folder missing
}
return names.filter((f) => {
if (!f.toLowerCase().endsWith(`.iso${COPY_SUFFIX}`)) return false
try {
rmSync(join(isosDir, f))

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

*.iso.part isn't only ours. Firefox downloads to <name>.iso.part next to the final file, and people do point downloads at the ISOs folder. Starting the app during a Firefox download of an ISO would delete the half-done download, and Firefox then fails it. Our copies should use a suffix nobody else uses (say .iso.vmm-copy), and this should only remove that one.

return true
} catch {
return false
}
})
}

const same = (a: string, b: string) => a.toLowerCase() === b.toLowerCase() // Windows paths

/**
Expand Down
21 changes: 19 additions & 2 deletions tests/isos.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { defaultConfig } from '@shared/config'
import { importIso, listIsos, watchFolder } from '../src/main/isos'
import { COPY_SUFFIX, importIso, listIsos, removeUnfinishedCopies, watchFolder } from '../src/main/isos'

let dir: string
beforeEach(() => {
Expand Down Expand Up @@ -110,7 +110,7 @@ describe('importIso', () => {
expect(readdirSync(isos)).toEqual([])
})

it('copies into the ISOs folder without leaving a .part file', async () => {
it('copies into the ISOs folder without leaving a temp file', async () => {
const file = join(src, 'debian.iso')
writeFileSync(file, 'abc')
const out = await importIso(file, isos, 'copy')
Expand Down Expand Up @@ -166,3 +166,20 @@ describe('importIso while a copy is running', () => {
expect(readFileSync(b, 'utf8')).toBe('small')
})
})

describe('removeUnfinishedCopies', () => {
it('deletes our unfinished copies and leaves everything else', () => {
writeFileSync(join(dir, 'kali.iso'), 'iso')
writeFileSync(join(dir, `kali (2).iso${COPY_SUFFIX}`), 'half')
writeFileSync(join(dir, `BIG.ISO${COPY_SUFFIX.toUpperCase()}`), 'half')
// Firefox writes its downloads like this, one may be in progress right now
writeFileSync(join(dir, 'debian.iso.part'), 'downloading')
writeFileSync(join(dir, 'notes.vmm-copy'), 'not an iso')
expect(removeUnfinishedCopies(dir).sort()).toEqual([`BIG.ISO${COPY_SUFFIX.toUpperCase()}`, `kali (2).iso${COPY_SUFFIX}`])
expect(readdirSync(dir).sort()).toEqual(['debian.iso.part', 'kali.iso', 'notes.vmm-copy'])
})

it('copes with a missing folder', () => {
expect(removeUnfinishedCopies(join(dir, 'nope'))).toEqual([])
})
})
Loading