Skip to content

Commit 71c4f2a

Browse files
committed
Optimize ccache usage
1 parent a980309 commit 71c4f2a

5 files changed

Lines changed: 257 additions & 13 deletions

File tree

‎.github/actions/initialize-build-environment/action.yml‎

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,10 @@ inputs:
1212
description: Restore and save build environment caches
1313
required: false
1414
default: 'true'
15+
use_ccache:
16+
description: Install ccache
17+
required: false
18+
default: 'true'
1519

1620
runs:
1721
using: "composite"
@@ -33,13 +37,41 @@ runs:
3337
run: |
3438
sudo apt update
3539
sudo apt-get -y install `
36-
build-essential ninja-build ccache file binutils patchelf p7zip-full pkg-config squashfs-tools tar xz-utils zip unzip curl git `
40+
build-essential ninja-build file binutils patchelf p7zip-full pkg-config squashfs-tools tar xz-utils zip unzip curl git `
3741
autoconf autoconf-archive automake libtool libltdl-dev bison flex m4 perl python3 python3-venv `
3842
libasound2-dev libatopology-dev `
3943
libxrandr-dev libxinerama-dev libxrender-dev libxcomposite-dev libxcursor-dev `
4044
libgl1-mesa-dev libxkbcommon-x11-0 libxcb-cursor0 libxcb-icccm4 libxcb-image0 libxcb-keysyms1 libxcb-render-util0 libxcb-xinerama0 libzstd-dev `
4145
protobuf-compiler desktop-file-utils
4246
47+
# TODO remove this after Ubuntu Packages' ccache updated to 4.14.2
48+
- name: Install CCache (Linux)
49+
if: runner.os == 'Linux' && inputs.use_ccache == 'true'
50+
shell: pwsh
51+
run: |
52+
$ErrorActionPreference = 'Stop'
53+
if ($env:RUNNER_ARCH -ne 'X64') {
54+
throw 'Unsupported ccache architecture'
55+
}
56+
$version = '4.14.2'
57+
$archiveName = "ccache-$version-linux-x86_64-musl-static.tar.gz"
58+
$directory = Join-Path $env:RUNNER_TEMP ("ccache-" + [guid]::NewGuid())
59+
New-Item -ItemType Directory -Path $directory | Out-Null
60+
$archive = Join-Path $directory $archiveName
61+
Invoke-WebRequest -Uri "https://github.com/ccache/ccache/releases/download/v$version/$archiveName" -OutFile $archive
62+
if ((Get-FileHash -LiteralPath $archive -Algorithm SHA256).Hash -ne 'd540ba01f160addbd3dd5e18eda9bd34005591b095c09ac8ae9d0a1b655e7ef5') {
63+
throw 'The ccache archive checksum does not match the release checksum'
64+
}
65+
& tar -xzf $archive -C $directory
66+
if ($LASTEXITCODE -ne 0) {
67+
throw 'The ccache archive could not be extracted'
68+
}
69+
$executables = @(Get-ChildItem -LiteralPath $directory -Recurse -File -Filter ccache)
70+
if ($executables.Count -ne 1) {
71+
throw 'The ccache archive does not contain exactly one ccache executable'
72+
}
73+
$executables[0].DirectoryName >> $env:GITHUB_PATH
74+
4375
- name: Install AppImage tools (Linux)
4476
if: runner.os == 'Linux'
4577
shell: pwsh

‎.github/workflows/build.yml‎

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ on:
2323
use_ccache:
2424
required: false
2525
type: boolean
26-
default: false
26+
default: true
2727
outputs:
2828
semver:
2929
value: ${{ jobs.Prepare.outputs.semver }}
@@ -88,12 +88,14 @@ jobs:
8888
BUILD_DIR: ${{ github.workspace }}/build/build
8989
INSTALL_DIR: ${{ github.workspace }}/build/install
9090
CCACHE_DIR: ${{ github.workspace }}/build/ccache
91+
CCACHE_MAXSIZE: '0'
92+
CCACHE_KEY_PREFIX: ccache-${{ matrix.os }}-${{ matrix.arch }}-
9193
BUILD_TYPE: ${{ inputs.build_type }}
9294
VERSION_IDENTIFIER: ${{ needs.Prepare.outputs.version_identifier }}
9395
EXPECTED_SEMVER: ${{ needs.Prepare.outputs.semver }}
9496
ARTIFACT_PLATFORM: ${{ matrix.platform }}
9597
ARTIFACT_ARCH: ${{ matrix.arch }}
96-
USE_CCACHE: ${{ inputs.build_type != 'nightly' && inputs.use_cache && inputs.use_ccache }}
98+
USE_CCACHE: ${{ inputs.use_cache && inputs.use_ccache }}
9799
steps:
98100
- name: Checkout repository
99101
uses: actions/checkout@v4
@@ -113,7 +115,8 @@ jobs:
113115
uses: ./.github/actions/initialize-build-environment
114116
with:
115117
qt_version: ${{ env.QT_VERSION }}
116-
use_cache: ${{ inputs.build_type != 'nightly' && inputs.use_cache }}
118+
use_cache: ${{ inputs.use_cache }}
119+
use_ccache: ${{ inputs.use_cache && inputs.use_ccache }}
117120

118121
- name: Download dspm
119122
id: download_dspm
@@ -127,7 +130,7 @@ jobs:
127130
variant: standalone
128131
directory: ${{ runner.temp }}/dspm-download
129132
fail-on-no-match: 'true'
130-
cache: ${{ inputs.build_type != 'nightly' && inputs.use_cache }}
133+
cache: ${{ inputs.use_cache }}
131134

132135
- name: Download dssp
133136
id: download_dssp
@@ -141,7 +144,7 @@ jobs:
141144
variant: portable
142145
directory: ${{ runner.temp }}/dssp-download
143146
fail-on-no-match: 'true'
144-
cache: ${{ inputs.build_type != 'nightly' && inputs.use_cache }}
147+
cache: ${{ inputs.use_cache }}
145148

146149
- name: Extract dssp
147150
if: steps.download_dssp.outputs.matched == 'true'
@@ -173,16 +176,19 @@ jobs:
173176
VCPKG_KEEP_ENV_VARS: VCPKG_BUILD_TYPE;MACOSX_DEPLOYMENT_TARGET
174177
with:
175178
qt-dir: ${{ env.QT_ROOT_DIR }}
176-
cache: ${{ inputs.build_type != 'nightly' && inputs.use_cache }}
179+
cache: ${{ inputs.use_cache }}
177180

178181
- name: Restore CCache cache
179-
if: inputs.build_type != 'nightly' && inputs.use_cache && inputs.use_ccache
182+
if: inputs.use_cache && inputs.use_ccache
180183
uses: actions/cache/restore@v4
181184
with:
182185
path: ${{ env.CCACHE_DIR }}
183-
key: ${{ runner.os }}-ccache-${{ inputs.source_sha }}
184-
restore-keys: |
185-
${{ runner.os }}-ccache-
186+
key: ${{ env.CCACHE_KEY_PREFIX }}${{ github.run_id }}-${{ github.run_attempt }}
187+
restore-keys: ${{ env.CCACHE_KEY_PREFIX }}
188+
189+
- name: Prepare CCache
190+
if: inputs.use_cache && inputs.use_ccache
191+
run: ./scripts/ci/Manage-CCache.ps1 -Operation prepare
186192

187193
- name: Build
188194
env:
@@ -213,12 +219,17 @@ jobs:
213219
"APPLICATION_NAME=$($output.ApplicationName)" >> $env:GITHUB_ENV
214220
"INSTALLER_FILE_BASE=$($output.InstallerFileBase)" >> $env:GITHUB_ENV
215221
222+
- name: Prepare CCache snapshot
223+
id: ccache_snapshot
224+
if: inputs.use_cache && inputs.use_ccache && github.event_name != 'pull_request' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch)
225+
run: ./scripts/ci/Manage-CCache.ps1 -Operation snapshot
226+
216227
- name: Save CCache cache
217-
if: inputs.build_type != 'nightly' && inputs.use_cache && inputs.use_ccache
228+
if: steps.ccache_snapshot.outputs.save == 'true'
218229
uses: actions/cache/save@v4
219230
with:
220231
path: ${{ env.CCACHE_DIR }}
221-
key: ${{ runner.os }}-ccache-${{ inputs.source_sha }}
232+
key: ${{ env.CCACHE_KEY_PREFIX }}${{ github.run_id }}-${{ github.run_attempt }}
222233

223234
- name: Collect symbol files
224235
env:
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# SPDX-FileCopyrightText: Team OpenVPI
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
name: Clean CCache
5+
6+
on:
7+
workflow_run:
8+
workflows: [Dev Build, Nightly Build]
9+
types: [completed]
10+
branches: [main]
11+
workflow_dispatch:
12+
13+
permissions:
14+
contents: read
15+
actions: write
16+
17+
concurrency:
18+
group: cleanup-ccache
19+
cancel-in-progress: false
20+
21+
jobs:
22+
Clean:
23+
runs-on: ubuntu-latest
24+
steps:
25+
- name: Checkout cleanup script
26+
uses: actions/checkout@v4
27+
with:
28+
ref: ${{ github.event.repository.default_branch }}
29+
sparse-checkout: scripts/ci/Clean-CCache.ps1
30+
sparse-checkout-cone-mode: false
31+
persist-credentials: false
32+
33+
- name: Clean CCache snapshots
34+
shell: pwsh
35+
env:
36+
GH_TOKEN: ${{ github.token }}
37+
DEFAULT_BRANCH: ${{ github.event.repository.default_branch }}
38+
run: ./scripts/ci/Clean-CCache.ps1 -Repository $env:GITHUB_REPOSITORY -DefaultBranch $env:DEFAULT_BRANCH

‎scripts/ci/Clean-CCache.ps1‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
# SPDX-FileCopyrightText: Team OpenVPI
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
param(
5+
[Parameter(Mandatory)]
6+
[ValidatePattern('^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$')]
7+
[string]$Repository,
8+
9+
[Parameter(Mandatory)]
10+
[string]$DefaultBranch
11+
)
12+
13+
$ErrorActionPreference = 'Stop'
14+
$headers = @{
15+
Accept = 'application/vnd.github+json'
16+
Authorization = "Bearer $env:GH_TOKEN"
17+
'X-GitHub-Api-Version' = '2022-11-28'
18+
}
19+
$apiUrl = "https://api.github.com/repos/$Repository/actions/caches"
20+
$caches = [System.Collections.Generic.Dictionary[long, object]]::new()
21+
for ($page = 1; ; $page++) {
22+
$response = Invoke-RestMethod -Uri "${apiUrl}?per_page=100&page=$page" -Headers $headers
23+
foreach ($cache in $response.actions_caches) {
24+
$caches[[long]$cache.id] = $cache
25+
}
26+
if ($response.actions_caches.Count -lt 100) {
27+
break
28+
}
29+
}
30+
31+
$groups = @{}
32+
$deletions = [System.Collections.Generic.List[object]]::new()
33+
$defaultRef = "refs/heads/$DefaultBranch"
34+
foreach ($cache in $caches.Values) {
35+
if ($cache.key -cnotmatch '(^|-)ccache-') {
36+
continue
37+
}
38+
if ($cache.ref -ne $defaultRef -or $cache.key -cnotmatch '^ccache-(?<environment>[a-z0-9][a-z0-9.-]*-(?:amd64|arm64))-[0-9]+-[0-9]+$') {
39+
$deletions.Add($cache)
40+
continue
41+
}
42+
$environment = $Matches.environment
43+
if (-not $groups.ContainsKey($environment)) {
44+
$groups[$environment] = [System.Collections.Generic.List[object]]::new()
45+
}
46+
$groups[$environment].Add($cache)
47+
}
48+
49+
foreach ($group in $groups.Values) {
50+
$ordered = @($group | Sort-Object -Property @{ Expression = { [System.DateTimeOffset]$_.created_at }; Descending = $true }, @{ Expression = { [long]$_.id }; Descending = $true })
51+
Write-Host "Retaining ccache snapshot: $($ordered[0].key)"
52+
for ($index = 1; $index -lt $ordered.Count; $index++) {
53+
$deletions.Add($ordered[$index])
54+
}
55+
}
56+
57+
$deletedCount = 0
58+
$deletedBytes = 0L
59+
foreach ($cache in $deletions) {
60+
Write-Host "Deleting ccache snapshot: $($cache.key) ($($cache.ref))"
61+
Invoke-RestMethod -Uri "$apiUrl/$($cache.id)" -Method Delete -Headers $headers -SkipHttpErrorCheck -StatusCodeVariable deleteStatus | Out-Null
62+
if ($deleteStatus -eq 204) {
63+
$deletedCount++
64+
$deletedBytes += [long]$cache.size_in_bytes
65+
} elseif ($deleteStatus -ne 404) {
66+
throw "Cache deletion failed with HTTP status $deleteStatus"
67+
}
68+
}
69+
70+
$deletedMiB = ($deletedBytes / 1MB).ToString('F1', [System.Globalization.CultureInfo]::InvariantCulture)
71+
Write-Host "Deleted $deletedCount ccache snapshots and released $deletedMiB MiB"
72+
if ($env:GITHUB_STEP_SUMMARY) {
73+
"Deleted $deletedCount ccache snapshots and released $deletedMiB MiB." >> $env:GITHUB_STEP_SUMMARY
74+
}

‎scripts/ci/Manage-CCache.ps1‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
# SPDX-FileCopyrightText: Team OpenVPI
2+
# SPDX-License-Identifier: Apache-2.0
3+
4+
param(
5+
[Parameter(Mandatory)]
6+
[ValidateSet('prepare', 'snapshot')]
7+
[string]$Operation
8+
)
9+
10+
$ErrorActionPreference = 'Stop'
11+
$workspacePath = [System.IO.Path]::GetFullPath($env:GITHUB_WORKSPACE)
12+
$buildPath = Join-Path $workspacePath 'build'
13+
$cachePath = Join-Path $buildPath 'ccache'
14+
$sourcePath = Join-Path $buildPath 'ccache-source'
15+
if ([System.IO.Path]::GetFullPath($env:CCACHE_DIR) -ne $cachePath) {
16+
throw 'The ccache directory must be the build/ccache directory of the workspace'
17+
}
18+
19+
if ($Operation -eq 'prepare') {
20+
$versionOutput = ccache --print-version
21+
if ($LASTEXITCODE -ne 0) {
22+
throw 'The ccache version could not be determined'
23+
}
24+
$installedVersion = [System.Version]::Parse(($versionOutput -join '').Trim())
25+
if ($installedVersion -lt [System.Version]'4.14') {
26+
throw 'CCache 4.14 or later is required'
27+
}
28+
Write-Host "CCache version: $installedVersion"
29+
30+
if (Test-Path -LiteralPath $sourcePath) {
31+
throw 'The ccache source directory already exists'
32+
}
33+
if (Test-Path -LiteralPath $cachePath) {
34+
Move-Item -LiteralPath $cachePath -Destination $sourcePath
35+
} else {
36+
New-Item -ItemType Directory -Path $sourcePath -Force | Out-Null
37+
}
38+
New-Item -ItemType Directory -Path $cachePath | Out-Null
39+
40+
$sourceUri = [System.Uri]::new($sourcePath, [System.UriKind]::Absolute).AbsoluteUri
41+
"CCACHE_REMOTE_STORAGE=$sourceUri @layout=local" >> $env:GITHUB_ENV
42+
'CCACHE_COMPILERCHECK=content' >> $env:GITHUB_ENV
43+
'CCACHE_HARDLINK=false' >> $env:GITHUB_ENV
44+
'CCACHE_FILECLONE=false' >> $env:GITHUB_ENV
45+
exit 0
46+
}
47+
48+
function Get-CacheEntries([string]$Directory) {
49+
$entries = [System.Collections.Generic.Dictionary[string, System.IO.FileInfo]]::new([System.StringComparer]::Ordinal)
50+
foreach ($file in (Get-ChildItem -LiteralPath $Directory -Recurse -File)) {
51+
$key = [System.IO.Path]::GetRelativePath($Directory, $file.FullName).Replace('\', '').Replace('/', '')
52+
if ($key -cmatch '^[0-9a-f]{40}$') {
53+
$entries.Add($key, $file)
54+
}
55+
}
56+
return ,$entries
57+
}
58+
59+
$sourceEntries = Get-CacheEntries $sourcePath
60+
$currentEntries = Get-CacheEntries $cachePath
61+
$changed = $currentEntries.Count -ne $sourceEntries.Count
62+
if (-not $changed) {
63+
foreach ($entry in $currentEntries.GetEnumerator()) {
64+
if (-not $sourceEntries.ContainsKey($entry.Key) -or $entry.Value.Length -ne $sourceEntries[$entry.Key].Length) {
65+
$changed = $true
66+
break
67+
}
68+
}
69+
}
70+
if (-not $changed) {
71+
foreach ($entry in $currentEntries.GetEnumerator()) {
72+
$currentHash = (Get-FileHash -LiteralPath $entry.Value.FullName -Algorithm SHA256).Hash
73+
$sourceHash = (Get-FileHash -LiteralPath $sourceEntries[$entry.Key].FullName -Algorithm SHA256).Hash
74+
if ($currentHash -ne $sourceHash) {
75+
$changed = $true
76+
break
77+
}
78+
}
79+
}
80+
81+
$save = $changed -and $currentEntries.Count -gt 0
82+
Write-Host "CCache entries: $($sourceEntries.Count) restored, $($currentEntries.Count) retained"
83+
if ($save) {
84+
ccache --recompress 10 | Write-Host
85+
if ($LASTEXITCODE -ne 0) {
86+
throw 'The ccache snapshot could not be recompressed'
87+
}
88+
}
89+
"save=$($save.ToString().ToLowerInvariant())" >> $env:GITHUB_OUTPUT

0 commit comments

Comments
 (0)