Address toolcache cleanup review feedback

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Henry MercerandCopilot App committed 2026-09-08 15:55:41 +01:00
1 parent deece8f852
commit 40a6b38247
4 files changed
+172 -59

No files matched your search

+13 -10
View File
@@ -151786,9 +151786,9 @@ async function downloadAndExtractZstdWithStreaming(codeqlURL, dest, authorizatio
}
await extractTarZst(response, dest, tarVersion, logger);
}
function getToolcacheToolDirectory() {
function getToolcacheToolDirectory(env) {
return path12.join(
getRequiredEnvParam("RUNNER_TOOL_CACHE"),
env.getRequired("RUNNER_TOOL_CACHE" /* RUNNER_TOOL_CACHE */),
TOOLCACHE_TOOL_NAME
);
}
@@ -151797,7 +151797,7 @@ function getToolcacheVersionDirectoryName(version) {
}
function getToolcacheDirectory(version) {
return path12.join(
getToolcacheToolDirectory(),
getToolcacheToolDirectory(getEnv()),
getToolcacheVersionDirectoryName(version),
os4.arch() || ""
);
@@ -151812,13 +151812,16 @@ function isToolcacheOnWorkspaceFilesystem(logger) {
return false;
}
}
async function deleteToolcacheBundles(logger) {
async function deleteToolcacheBundles({
env,
logger
}) {
let toolDirectory;
try {
toolDirectory = getToolcacheToolDirectory();
toolDirectory = getToolcacheToolDirectory(env);
} catch (e) {
logger.info(
`Unable to reclaim disk space from the toolcache: ${getErrorMessage(e)}`
`Unable to determine toolcache directory: ${getErrorMessage(e)}`
);
return { deletedVersions: [], failed: true };
}
@@ -151848,13 +151851,13 @@ async function deleteToolcacheBundles(logger) {
const deletedVersions = [];
let failed = false;
for (const entry of entries) {
const versionDirectory = path12.join(toolDirectory, entry.name);
if (!entry.isDirectory()) {
logger.debug(
`Not deleting '${versionDirectory}' from the toolcache since it is not a directory.`
`Not deleting '${entry.name}' from the CodeQL toolcache since it is not a directory.`
);
continue;
}
const versionDirectory = path12.join(toolDirectory, entry.name);
try {
await fs13.promises.rm(versionDirectory, {
force: true,
@@ -151874,7 +151877,7 @@ async function deleteToolcacheBundles(logger) {
return { deletedVersions: deletedVersions.sort(), failed };
} catch (e) {
logger.info(
`Failed to read the CodeQL tools at '${toolDirectory}' from the toolcache: ${getErrorMessage(e)}`
`Failed to clean up the CodeQL toolcache at '${toolDirectory}': ${getErrorMessage(e)}`
);
return { deletedVersions: [], failed: true };
}
@@ -152429,7 +152432,7 @@ async function tryDeleteToolcacheBundles({
if (!isGitHubHostedRunner() || !isToolcacheOnWorkspaceFilesystem(logger) || !await features.getValue("cleanup_toolcache_bundles" /* CleanupToolcacheBundles */)) {
return;
}
const result = await deleteToolcacheBundles(logger);
const result = await deleteToolcacheBundles({ env, logger });
addNoLanguageDiagnostic(
void 0,
makeTelemetryDiagnostic(
+141 -34
View File
@@ -10,7 +10,7 @@ import * as sinon from "sinon";
import * as actionsUtil from "./actions-util";
import * as api from "./api-client";
import * as diagnostics from "./diagnostics";
import { ActionsEnvVars, EnvVar } from "./environment";
import { ActionsEnvVars, EnvVar, ReadOnlyEnv } from "./environment";
import { Feature } from "./feature-flags";
import { getRunnerLogger } from "./logging";
import { getCacheRestoreKeyPrefix } from "./overlay/caching";
@@ -966,16 +966,18 @@ function createToolcacheEntry(
}
/**
* Stubs out the download and the diagnostic sink, then downloads the CodeQL tools into a toolcache
* rooted at `toolcacheRoot`.
* Stubs out the download and the diagnostic sink, then downloads the CodeQL tools.
*
* @returns the attributes of the toolcache cleanup diagnostic, or `undefined` if we didn't emit one.
* @returns the extraction directory and the toolcache cleanup diagnostic, if emitted.
*/
async function runDownloadCodeQL(
toolcacheRoot: string,
features: Feature[],
bundleVersion: string | undefined = CLEANUP_BUNDLE_VERSION,
): Promise<toolsDownload.ToolcacheCleanupResult | undefined> {
bundleVersion: string | undefined,
): Promise<{
codeqlFolder: string;
cleanupDiagnostic: toolsDownload.ToolcacheCleanupResult | undefined;
}> {
sinon
.stub(toolsDownload, "downloadAndExtract")
.callsFake(async (_url, _compressionMethod, dest) => {
@@ -986,7 +988,7 @@ async function runDownloadCodeQL(
});
const addDiagnostic = sinon.stub(diagnostics, "addNoLanguageDiagnostic");
await setupCodeql.downloadCodeQL(
const { codeqlFolder } = await setupCodeql.downloadCodeQL(
"https://example.com/codeql-bundle.tar.gz",
"gzip",
bundleVersion,
@@ -1003,9 +1005,12 @@ async function runDownloadCodeQL(
.map((call) => call.args[1])
.find((d) => d.source?.id === "codeql-action/toolcache-bundle-cleanup");
return diagnostic?.attributes as
| toolsDownload.ToolcacheCleanupResult
| undefined;
return {
codeqlFolder,
cleanupDiagnostic: diagnostic?.attributes as
| toolsDownload.ToolcacheCleanupResult
| undefined,
};
}
/**
@@ -1051,7 +1056,11 @@ async function testToolcacheCleanup(
);
const otherToolDirectory = createToolcacheEntry(tmpDir, "Node", "20.0.0");
const cleanupDiagnostic = await runDownloadCodeQL(tmpDir, features);
const { cleanupDiagnostic } = await runDownloadCodeQL(
tmpDir,
features,
CLEANUP_BUNDLE_VERSION,
);
t.true(
fs.existsSync(otherToolDirectory),
@@ -1153,9 +1162,11 @@ test.serial(
// A toolcache with other tools in it, but no CodeQL.
const otherToolDirectory = createToolcacheEntry(tmpDir, "Node", "20.0.0");
const cleanupDiagnostic = await runDownloadCodeQL(tmpDir, [
Feature.CleanupToolcacheBundles,
]);
const { cleanupDiagnostic } = await runDownloadCodeQL(
tmpDir,
[Feature.CleanupToolcacheBundles],
CLEANUP_BUNDLE_VERSION,
);
t.true(fs.existsSync(otherToolDirectory));
t.deepEqual(cleanupDiagnostic, { deletedVersions: [], failed: false });
@@ -1181,9 +1192,11 @@ test.serial(
.stub(fs.promises, "rm")
.rejects(new Error("EACCES: permission denied"));
const cleanupDiagnostic = await runDownloadCodeQL(tmpDir, [
Feature.CleanupToolcacheBundles,
]);
const { cleanupDiagnostic } = await runDownloadCodeQL(
tmpDir,
[Feature.CleanupToolcacheBundles],
CLEANUP_BUNDLE_VERSION,
);
// Restore before `withTmpDir` cleans up after itself.
rmStub.restore();
@@ -1201,17 +1214,94 @@ test.serial(
test.serial(
"deleteToolcacheBundles reports a failure when the toolcache location is unknown",
async (t) => {
delete process.env[ActionsEnvVars.RUNNER_TOOL_CACHE];
const messages: LoggedMessage[] = [];
const result = await toolsDownload.deleteToolcacheBundles(
getRunnerLogger(true),
);
const result = await toolsDownload.deleteToolcacheBundles({
env: new ReadOnlyEnv({}),
logger: getRecordingLogger(messages),
});
t.deepEqual(
result,
{ deletedVersions: [], failed: true },
"Should report a failure rather than throwing, so the download can continue.",
);
checkExpectedLogMessages(t, messages, [
"Unable to determine toolcache directory: RUNNER_TOOL_CACHE environment variable must be set",
]);
},
);
test.serial(
"deleteToolcacheBundles uses the supplied environment rather than process.env",
async (t) => {
await withTmpDir(async (tmpDir) => {
const ambientRoot = path.join(tmpDir, "ambient");
const injectedRoot = path.join(tmpDir, "injected");
setupActionsVars(tmpDir, ambientRoot);
const ambientVersion = createToolcacheEntry(
ambientRoot,
"CodeQL",
CLEANUP_STALE_VERSION,
);
const injectedVersion = createToolcacheEntry(
injectedRoot,
"CodeQL",
CLEANUP_STALE_VERSION,
);
const fileEntry = path.join(injectedRoot, "CodeQL", "not-a-directory");
fs.writeFileSync(fileEntry, "keep");
const result = await toolsDownload.deleteToolcacheBundles({
env: new ReadOnlyEnv({
[ActionsEnvVars.RUNNER_TOOL_CACHE]: injectedRoot,
}),
logger: getRunnerLogger(true),
});
t.deepEqual(result, {
deletedVersions: [CLEANUP_STALE_VERSION],
failed: false,
});
t.false(fs.existsSync(injectedVersion));
t.true(fs.existsSync(ambientVersion));
t.is(fs.readFileSync(fileEntry, "utf8"), "keep");
});
},
);
test.serial(
"deleteToolcacheBundles reports a failure when the toolcache directory cannot be read",
async (t) => {
await withTmpDir(async (tmpDir) => {
const versionDirectory = createToolcacheEntry(
tmpDir,
"CodeQL",
CLEANUP_STALE_VERSION,
);
const messages: LoggedMessage[] = [];
const readdir = sinon
.stub(fs.promises, "readdir")
.rejects(new Error("permission denied"));
try {
const result = await toolsDownload.deleteToolcacheBundles({
env: new ReadOnlyEnv({
[ActionsEnvVars.RUNNER_TOOL_CACHE]: tmpDir,
}),
logger: getRecordingLogger(messages),
});
t.deepEqual(result, { deletedVersions: [], failed: true });
t.true(fs.existsSync(versionDirectory));
checkExpectedLogMessages(t, messages, [
`Failed to clean up the CodeQL toolcache at '${path.join(tmpDir, "CodeQL")}': permission denied`,
]);
} finally {
readdir.restore();
}
});
},
);
@@ -1234,9 +1324,11 @@ test.serial(
path.join(toolcacheRoot, "CodeQL"),
);
const cleanupDiagnostic = await runDownloadCodeQL(toolcacheRoot, [
Feature.CleanupToolcacheBundles,
]);
const { cleanupDiagnostic } = await runDownloadCodeQL(
toolcacheRoot,
[Feature.CleanupToolcacheBundles],
CLEANUP_BUNDLE_VERSION,
);
t.true(
fs.existsSync(
@@ -1322,12 +1414,16 @@ test.serial(
CLEANUP_STALE_VERSION,
);
const cleanupDiagnostic = await runDownloadCodeQL(
const { codeqlFolder, cleanupDiagnostic } = await runDownloadCodeQL(
tmpDir,
[Feature.CleanupToolcacheBundles],
undefined, // bundleVersion
);
t.is(path.dirname(codeqlFolder), tmpDir);
t.not(codeqlFolder, path.join(tmpDir, "CodeQL"));
t.true(fs.existsSync(codeqlFolder));
t.false(fs.existsSync(`${codeqlFolder}.complete`));
t.false(fs.existsSync(staleDirectory));
t.deepEqual(cleanupDiagnostic, {
deletedVersions: [CLEANUP_STALE_VERSION],
@@ -1352,9 +1448,11 @@ test.serial(
}),
);
const cleanupDiagnostic = await runDownloadCodeQL(tmpDir, [
Feature.CleanupToolcacheBundles,
]);
const { cleanupDiagnostic } = await runDownloadCodeQL(
tmpDir,
[Feature.CleanupToolcacheBundles],
CLEANUP_BUNDLE_VERSION,
);
lstatStub.restore();
@@ -1386,9 +1484,11 @@ test.serial(
.stub(toolsDownload, "isToolcacheOnWorkspaceFilesystem")
.returns(false);
const cleanupDiagnostic = await runDownloadCodeQL(tmpDir, [
Feature.CleanupToolcacheBundles,
]);
const { cleanupDiagnostic } = await runDownloadCodeQL(
tmpDir,
[Feature.CleanupToolcacheBundles],
CLEANUP_BUNDLE_VERSION,
);
t.true(fs.existsSync(staleDirectory));
t.is(cleanupDiagnostic, undefined);
@@ -1434,14 +1534,21 @@ test.serial(
path.join(toolcacheRoot, "CodeQL", "9.9.9"),
);
const cleanupDiagnostic = await runDownloadCodeQL(toolcacheRoot, [
Feature.CleanupToolcacheBundles,
]);
const { cleanupDiagnostic } = await runDownloadCodeQL(
toolcacheRoot,
[Feature.CleanupToolcacheBundles],
CLEANUP_BUNDLE_VERSION,
);
t.true(
fs.existsSync(path.join(outsideDirectory, "contents")),
"Should not delete anything through a symlinked version directory.",
);
t.true(
fs
.lstatSync(path.join(toolcacheRoot, "CodeQL", "9.9.9"))
.isSymbolicLink(),
);
t.deepEqual(cleanupDiagnostic, {
deletedVersions: [CLEANUP_STALE_VERSION],
failed: false,
+1 -1
View File
@@ -908,7 +908,7 @@ async function tryDeleteToolcacheBundles({
return;
}
const result = await deleteToolcacheBundles(logger);
const result = await deleteToolcacheBundles({ env, logger });
addNoLanguageDiagnostic(
undefined,
+17 -14
View File
@@ -10,6 +10,8 @@ import * as toolcache from "@actions/tool-cache";
import { https } from "follow-redirects";
import * as semver from "semver";
import { ActionState } from "./action-common";
import { ActionsEnvVars, getEnv, ReadOnlyEnv } from "./environment";
import { formatDuration, Logger } from "./logging";
import * as tar from "./tar";
import { cleanUpPath, getErrorMessage, getRequiredEnvParam } from "./util";
@@ -198,9 +200,9 @@ async function downloadAndExtractZstdWithStreaming(
}
/** Gets the path to the toolcache directory that holds all versions of the CodeQL tools. */
function getToolcacheToolDirectory(): string {
function getToolcacheToolDirectory(env: ReadOnlyEnv): string {
return path.join(
getRequiredEnvParam("RUNNER_TOOL_CACHE"),
env.getRequired(ActionsEnvVars.RUNNER_TOOL_CACHE),
TOOLCACHE_TOOL_NAME,
);
}
@@ -213,7 +215,7 @@ function getToolcacheVersionDirectoryName(version: string): string {
/** Gets the path to the toolcache directory for the specified version of the CodeQL tools. */
export function getToolcacheDirectory(version: string): string {
return path.join(
getToolcacheToolDirectory(),
getToolcacheToolDirectory(getEnv()),
getToolcacheVersionDirectoryName(version),
os.arch() || "",
);
@@ -257,21 +259,22 @@ export interface ToolcacheCleanupResult {
* Only safe to call when we are about to download the tools, since that means we did not resolve
* them from the toolcache and so nothing in there is in use by this job.
*
* This only ever touches the CodeQL directory of the toolcache, and is best-effort: any failure is
* logged rather than propagated, since the caller can proceed without the disk space.
* This only ever touches the CodeQL directory of the toolcache. Cleanup errors are logged and
* returned as `failed: true` rather than thrown.
*
* @returns the versions that were deleted, and whether we hit an error while trying.
*/
export async function deleteToolcacheBundles(
logger: Logger,
): Promise<ToolcacheCleanupResult> {
export async function deleteToolcacheBundles({
env,
logger,
}: ActionState<["Logger", "ReadOnlyEnv"]>): Promise<ToolcacheCleanupResult> {
let toolDirectory: string;
try {
toolDirectory = getToolcacheToolDirectory();
toolDirectory = getToolcacheToolDirectory(env);
} catch (e) {
logger.info(
`Unable to reclaim disk space from the toolcache: ${getErrorMessage(e)}`,
`Unable to determine toolcache directory: ${getErrorMessage(e)}`,
);
return { deletedVersions: [], failed: true };
}
@@ -307,17 +310,17 @@ export async function deleteToolcacheBundles(
let failed = false;
for (const entry of entries) {
const versionDirectory = path.join(toolDirectory, entry.name);
// `isDirectory` is false for a symlink, so we never delete a version directory that is
// really somewhere else.
if (!entry.isDirectory()) {
logger.debug(
`Not deleting '${versionDirectory}' from the toolcache since it is not a directory.`,
`Not deleting '${entry.name}' from the CodeQL toolcache since it is not a directory.`,
);
continue;
}
const versionDirectory = path.join(toolDirectory, entry.name);
try {
await fs.promises.rm(versionDirectory, {
force: true,
@@ -338,7 +341,7 @@ export async function deleteToolcacheBundles(
return { deletedVersions: deletedVersions.sort(), failed };
} catch (e) {
logger.info(
`Failed to read the CodeQL tools at '${toolDirectory}' from the toolcache: ${getErrorMessage(e)}`,
`Failed to clean up the CodeQL toolcache at '${toolDirectory}': ${getErrorMessage(e)}`,
);
return { deletedVersions: [], failed: true };
}