diff --git a/src/cli/cleanup/cleanup-cache.service.ts b/src/cli/cleanup/cleanup-cache.service.ts index 7f70a29513..7b7ebea5e3 100644 --- a/src/cli/cleanup/cleanup-cache.service.ts +++ b/src/cli/cleanup/cleanup-cache.service.ts @@ -4,13 +4,7 @@ import { inject, injectable, multiInject, optional } from 'inversify'; import type { BaseInstallService } from '../install-tool/base-install.service.ts'; import { INSTALL_TOOL_TOKEN } from '../install-tool/install-tool.service.ts'; import { EnvService, PathService } from '../services/index.ts'; -import { logger, spawn } from '../utils/index.ts'; - -/** The paths of the entries in a folder, none for a missing folder. */ -async function listEntries(dir: string): Promise { - const entries = await fs.readdir(dir).catch(() => []); - return entries.map((entry) => join(dir, entry)); -} +import { listEntries, logger, removePath } from '../utils/index.ts'; /** Whether something exists at the path, also a dangling link. */ async function exists(path: string): Promise { @@ -23,37 +17,17 @@ async function contains(path: string, folder: string): Promise { return !!real && (folder === real || folder.startsWith(`${real}${sep}`)); } -/** - * Removes a file or folder. Folders which can't be removed because of their - * permissions, eg. the read-only go module cache, are made writable first. - * A link is never made writable, `chmod` would change its target. - */ -async function remove(path: string): Promise { - try { - await fs.rm(path, { recursive: true, force: true }); - } catch (err) { - if ( - (err as NodeJS.ErrnoException).code !== 'EACCES' || - (await fs.lstat(path)).isSymbolicLink() - ) { - throw err; - } - await spawn('chmod', ['-R', 'u+w', path]); - await fs.rm(path, { recursive: true, force: true }); - } -} - /** * Removes a cache folder. For a link only the contents of its target are * removed, so a redirect, eg. to a volume, is kept. */ async function removeCacheDir(path: string): Promise { if (!(await fs.lstat(path)).isSymbolicLink()) { - await remove(path); + await removePath(path); return; } for (const entry of await listEntries(path)) { - await remove(entry); + await removePath(entry); } } @@ -123,7 +97,7 @@ export class CleanupCacheService { } else { logger.debug({ path }, 'remove cache'); try { - await (roots.has(path) ? removeCacheDir(path) : remove(path)); + await (roots.has(path) ? removeCacheDir(path) : removePath(path)); } catch (err) { logger.warn({ path, err }, 'cannot remove cache'); failed++; diff --git a/src/cli/install-tool/install-tool.service.spec.ts b/src/cli/install-tool/install-tool.service.spec.ts index 05d8060ae0..687ba00cf8 100644 --- a/src/cli/install-tool/install-tool.service.spec.ts +++ b/src/cli/install-tool/install-tool.service.spec.ts @@ -410,6 +410,35 @@ describe('cli/install-tool/install-tool.service', () => { expect(logger.debug).toHaveBeenCalledWith('cleaning user caches'); }); + test('removes read-only user caches on a docker build', async () => { + vi.mocked(isDockerBuild).mockResolvedValue(true); + const { cachePath } = await child.getAsync(PathService); + const cacheDir = join(cachePath, '.cache'); + const image = join(cacheDir, 'virtualenv/wheel/image'); + await fs.mkdir(image, { recursive: true }); + await fs.writeFile(join(image, 'file'), ''); + await fs.chmod(image, 0o555); + const venv = join(cachePath, '.local/share/virtualenv'); + await fs.mkdir(venv, { recursive: true }); + + expect(await install.install('bun', '1.0.6')).toBeUndefined(); + + expect(await fs.readdir(cacheDir)).toEqual([]); + expect(await pathExists(venv)).toBe(false); + }); + + test('keeps the user caches on a dry run', async () => { + vi.mocked(isDockerBuild).mockResolvedValue(true); + const { cachePath } = await child.getAsync(PathService); + const file = join(cachePath, '.cache/tool/file'); + await fs.mkdir(join(file, '..'), { recursive: true }); + await fs.writeFile(file, ''); + + expect(await install.install('bun', '1.0.7', true)).toBeUndefined(); + + expect(await pathExists(file, 'file')).toBe(true); + }); + test('cleans the root caches when running as root', async () => { vi.mocked(isDockerBuild).mockResolvedValue(true); vi.spyOn(EnvService.prototype, 'isRoot', 'get').mockReturnValue(true); diff --git a/src/cli/install-tool/install-tool.service.ts b/src/cli/install-tool/install-tool.service.ts index a92c32aa15..ff60f7091a 100644 --- a/src/cli/install-tool/install-tool.service.ts +++ b/src/cli/install-tool/install-tool.service.ts @@ -24,7 +24,9 @@ import { cleanAptFiles, cleanTmpFiles, isDockerBuild, + listEntries, logger, + removePath, } from '../utils/index.ts'; import type { BaseInstallService } from './base-install.service'; import { @@ -214,23 +216,30 @@ export class InstallToolService { ); } else { logger.debug('cleaning user caches'); - await deleteAsync( - [ - path.join(this.pathSvc.cachePath, '.cache/**'), - path.join(this.pathSvc.cachePath, '.local/share/virtualenv'), - ], - { - force: true, - dryRun, - dot: true, - }, - ); + if (!dryRun) { + await this.cleanUserCaches(); + } } } await this.evictCache(dryRun); } + /** + * Removes the contents of the user `.cache` folder and the virtualenv cache. + * Read-only folders, eg. the virtualenv seed packages, are made writable + * first. + */ + private async cleanUserCaches(): Promise { + const { cachePath } = this.pathSvc; + for (const entry of [ + ...(await listEntries(path.join(cachePath, '.cache'))), + path.join(cachePath, '.local/share/virtualenv'), + ]) { + await removePath(entry); + } + } + /** * Evicts the oldest files from the download cache when the disk is too * full, see `CacheService.evict`. A failing eviction is only logged, as it diff --git a/src/cli/utils/common.ts b/src/cli/utils/common.ts index ac06ae7715..f6fb9d0077 100644 --- a/src/cli/utils/common.ts +++ b/src/cli/utils/common.ts @@ -1,6 +1,6 @@ import fs, { readFile, stat } from 'node:fs/promises'; import os from 'node:os'; -import { isAbsolute, relative, sep } from 'node:path'; +import { isAbsolute, join, relative, sep } from 'node:path'; import process from 'node:process'; import { deleteAsync } from 'del'; import { logger } from './logger.ts'; @@ -132,6 +132,51 @@ export function isInside(parent: string, child: string): boolean { return rel !== '..' && !rel.startsWith(`..${sep}`); } +/** The paths of the entries in a folder, none for a missing folder. */ +export async function listEntries(dir: string): Promise { + const entries = await fs.readdir(dir).catch(() => []); + return entries.map((entry) => join(dir, entry)); +} + +/** + * Gives the owner write permission on a folder and every folder below it, so + * their entries can be removed. Links are skipped, `chmod` would change their + * target. + * @param dir - the folder + * @param mode - the current mode of the folder + */ +async function makeWritable(dir: string, mode: number): Promise { + await fs.chmod(dir, (mode & 0o7777) | fs.constants.S_IWUSR); + for (const entry of await fs.readdir(dir, { withFileTypes: true })) { + if (entry.isDirectory()) { + const sub = join(dir, entry.name); + await makeWritable(sub, (await fs.lstat(sub)).mode); + } + } +} + +/** + * Removes a file or folder. Folders which can't be removed because of their + * permissions, eg. the read-only go module cache or the virtualenv seed + * packages, are made writable first. A link is never made writable, `chmod` + * would change its target. + */ +export async function removePath(path: string): Promise { + try { + await fs.rm(path, { recursive: true, force: true }); + } catch (err) { + const stats = await fs.lstat(path); + if ( + (err as NodeJS.ErrnoException).code !== 'EACCES' || + !stats.isDirectory() + ) { + throw err; + } + await makeWritable(path, stats.mode); + await fs.rm(path, { recursive: true, force: true }); + } +} + /** Removes the apt lists and logs left behind by package installs. */ export async function cleanAptFiles(dryRun = false): Promise { await deleteAsync(