Skip to content
Open
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
34 changes: 4 additions & 30 deletions src/cli/cleanup/cleanup-cache.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string[]> {
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<boolean> {
Expand All @@ -23,37 +17,17 @@ async function contains(path: string, folder: string): Promise<boolean> {
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<void> {
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<void> {
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);
}
}

Expand Down Expand Up @@ -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++;
Expand Down
29 changes: 29 additions & 0 deletions src/cli/install-tool/install-tool.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
31 changes: 20 additions & 11 deletions src/cli/install-tool/install-tool.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ import {
cleanAptFiles,
cleanTmpFiles,
isDockerBuild,
listEntries,
logger,
removePath,
} from '../utils/index.ts';
import type { BaseInstallService } from './base-install.service';
import {
Expand Down Expand Up @@ -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<void> {
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
Expand Down
47 changes: 46 additions & 1 deletion src/cli/utils/common.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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<string[]> {
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<void> {
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<void> {
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<void> {
await deleteAsync(
Expand Down