Unverified Commit d0681488 authored by Daz DeBoer's avatar Daz DeBoer Committed by GitHub
Browse files

Choose best Gradle version to use for cache cleanup (#526)

The cache-cleanup operation works by executing Gradle on a dummy project
and a custom init-script. The init-script requires at least Gradle 8.11
to work.

Ideally, the version of Gradle used for cleanup should be no older than
the newest one that wrote entries to Gradle User Home. If an older
Gradle version is used for cache-cleanup, it will not remove entries
written specifically for newer versions.

With this change, we now attempt to ensure that cache-cleanup is run
with the best Gradle version available. We inspect the Gradle version on
PATH to see if it is new enough, otherwise we will provision a Gradle
version equal to the newest one that ran in the Job.

The logic is:
- Determine the newest version of Gradle that was executed during the
Job. This is the 'minimum version' for cache cleanup.
- Inspect the Gradle version on PATH (if any) to see if it is equal to
or newer than the 'minimum version'.
- If the version Gradle on PATH is new enough, use that version for
cache-cleanup.
- If not, attempt to provision Gradle with the 'minimum version'.

Fixes #436
parents b426ffeb c6e631b4
Loading
Loading
Loading
Loading
+1 −1
Changes for .github/workflows/integ-test-provision-gradle-versions.yml: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -78,7 +78,7 @@ jobs:
    strategy:
      fail-fast: false
      matrix:
        gradle: ["8.12", 8.9, 8.1, 7.6.4, 6.9.4, 5.6.4, 4.10.3, 3.5.1]
        gradle: ["8.13-milestone-2", "8.12", "8.12-rc-1", 8.9, 8.1, 7.6.4, 6.9.4, 5.6.4, 4.10.3, 3.5.1]
        os: ${{fromJSON(inputs.runner-os)}}
        include:
          - java-version: 11
+4
Changes for build: 4 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -36,6 +36,10 @@ case "$1" in
        npm clean-install
        npm run build
        ;;
    test)
        shift
        npm test -- $@
        ;;
    *)
        npm run build
        ;;
+13
Changes for sources/src/build-results.ts: 13 added lines, 0 removed lines.
Original line number Diff line number Diff line
import * as fs from 'fs'
import * as path from 'path'
import {versionIsAtLeast} from './execution/gradle'

export interface BuildResult {
    get rootProjectName(): string
@@ -32,6 +33,18 @@ export class BuildResults {
        const allHomes = this.results.map(buildResult => buildResult.gradleHomeDir)
        return Array.from(new Set(allHomes))
    }

    highestGradleVersion(): string | null {
        if (this.results.length === 0) {
            return null
        }
        return this.results
            .map(result => result.gradleVersion)
            .reduce((maxVersion: string, currentVersion: string) => {
                if (!maxVersion) return currentVersion
                return versionIsAtLeast(currentVersion, maxVersion) ? currentVersion : maxVersion
            })
    }
}

export function loadBuildResults(): BuildResults {
+29 −6
Changes for sources/src/caching/cache-cleaner.ts: 29 added lines, 6 removed lines.
Original line number Diff line number Diff line
@@ -4,6 +4,8 @@ import * as exec from '@actions/exec'
import fs from 'fs'
import path from 'path'
import * as provisioner from '../execution/provision'
import {BuildResults} from '../build-results'
import {versionIsAtLeast} from '../execution/gradle'

export class CacheCleaner {
    private readonly gradleUserHome: string
@@ -21,13 +23,37 @@ export class CacheCleaner {
        return timestamp
    }

    async forceCleanup(): Promise<void> {
    async forceCleanup(buildResults: BuildResults): Promise<void> {
        const executable = await this.gradleExecutableForCleanup(buildResults)
        const cleanTimestamp = core.getState('clean-timestamp')
        await this.forceCleanupFilesOlderThan(cleanTimestamp)
        await this.forceCleanupFilesOlderThan(cleanTimestamp, executable)
    }

    /**
     * Attempt to use the newest Gradle version that was used to run a build, at least 8.11.
     *
     * This will avoid the need to provision a Gradle version for the cleanup when not necessary.
     */
    private async gradleExecutableForCleanup(buildResults: BuildResults): Promise<string> {
        const preferredVersion = buildResults.highestGradleVersion()
        if (preferredVersion && versionIsAtLeast(preferredVersion, '8.11')) {
            try {
                return await provisioner.provisionGradleAtLeast(preferredVersion)
            } catch (e) {
                // Ignore the case where the preferred version cannot be located in https://services.gradle.org/versions/all.
                // This can happen for snapshot Gradle versions.
                core.info(
                    `Failed to provision Gradle ${preferredVersion} for cache cleanup. Falling back to default version.`
                )
            }
        }

        // Fallback to the minimum version required for cache-cleanup
        return await provisioner.provisionGradleAtLeast('8.11')
    }

    // Visible for testing
    async forceCleanupFilesOlderThan(cleanTimestamp: string): Promise<void> {
    async forceCleanupFilesOlderThan(cleanTimestamp: string, executable: string): Promise<void> {
        // Run a dummy Gradle build to trigger cache cleanup
        const cleanupProjectDir = path.resolve(this.tmpDir, 'dummy-cleanup-project')
        fs.mkdirSync(cleanupProjectDir, {recursive: true})
@@ -55,9 +81,6 @@ export class CacheCleaner {
        )
        fs.writeFileSync(path.resolve(cleanupProjectDir, 'build.gradle'), 'task("noop") {}')

        // TODO: This is ineffective: we should be using the newest version of Gradle that ran a build, or a newer version if it's available on PATH.
        const executable = await provisioner.provisionGradleAtLeast('8.12')

        await core.group('Executing Gradle to clean up caches', async () => {
            core.info(`Cleaning up caches last used before ${cleanTimestamp}`)
            await this.executeCleanupBuild(executable, cleanupProjectDir)
+3 −3
Changes for sources/src/caching/caches.ts: 3 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -102,7 +102,7 @@ export async function save(
            cacheListener.setCacheCleanupDisabled(CLEANUP_DISABLED_DUE_TO_CONFIG_CACHE_HIT)
        } else if (cacheConfig.shouldPerformCacheCleanup(buildResults.anyFailed())) {
            cacheListener.setCacheCleanupEnabled()
            await performCacheCleanup(gradleUserHome)
            await performCacheCleanup(gradleUserHome, buildResults)
        } else {
            core.info('Not performing cache-cleanup due to build failure')
            cacheListener.setCacheCleanupDisabled(CLEANUP_DISABLED_DUE_TO_FAILURE)
@@ -114,10 +114,10 @@ export async function save(
    })
}

async function performCacheCleanup(gradleUserHome: string): Promise<void> {
async function performCacheCleanup(gradleUserHome: string, buildResults: BuildResults): Promise<void> {
    const cacheCleaner = new CacheCleaner(gradleUserHome, process.env['RUNNER_TEMP']!)
    try {
        await cacheCleaner.forceCleanup()
        await cacheCleaner.forceCleanup(buildResults)
    } catch (e) {
        core.warning(`Cache cleanup failed. Will continue. ${String(e)}`)
    }
Loading