Repository navigation
Expand file tree
/
Copy pathjdk-cache.ts
More file actions
252 lines (229 loc) · 7.41 KB
/
Copy pathjdk-cache.ts
File metadata and controls
252 lines (229 loc) · 7.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import {createHash} from 'crypto';
import fs from 'fs';
import path from 'path';
import * as cache from '@actions/cache';
import * as core from '@actions/core';
import {isCacheFeatureAvailable} from './cache-feature.js';
import type {SignatureVerificationKey} from './distributions/base-models.js';
const STATE_JDK_CACHES = 'jdk-caches';
const JDK_CACHE_KEY_VERSION = 1;
export interface JdkCache {
distribution: string;
packageType: string;
architecture: string;
version: string;
source: string;
verification: string;
path: string;
}
interface JdkCacheState {
key: string;
path: string;
architecture: string;
matchedKey?: string;
// Cheap identity of the installation that occupied `path` when the entry was
// registered. The tool-cache path is shared per version/architecture, so a
// later step (e.g. one using `force-download`) can replace those bytes; the
// post-job save must not upload content that does not match the identity the
// key was computed for.
installation?: string;
}
const restoredCaches: JdkCacheState[] = [];
export async function restoreJdk(jdk: JdkCache): Promise<boolean> {
if (!jdk.path || !isCacheFeatureAvailable()) {
return false;
}
const key = buildJdkCacheKey(jdk);
let matchedKey: string | undefined;
try {
matchedKey = await cache.restoreCache([jdk.path], key);
} catch (error) {
core.warning(`Failed to restore JDK cache: ${(error as Error).message}`);
}
const architecturePath = path.join(jdk.path, jdk.architecture);
if (
matchedKey &&
(!fs.existsSync(architecturePath) ||
!fs.existsSync(`${architecturePath}.complete`))
) {
core.warning(
`JDK cache key ${matchedKey} was restored without the expected tool-cache path; downloading the JDK instead.`
);
matchedKey = undefined;
}
recordJdkCache({
key,
path: jdk.path,
architecture: jdk.architecture,
matchedKey
});
if (matchedKey) {
core.info(`JDK cache restored from key: ${matchedKey}`);
return true;
}
core.info(`JDK cache is not found for ${jdk.distribution} ${jdk.version}`);
return false;
}
export function registerJdk(jdk: JdkCache): void {
if (!jdk.path) {
return;
}
recordJdkCache({
key: buildJdkCacheKey(jdk),
path: jdk.path,
architecture: jdk.architecture,
installation: getInstallationIdentity(jdk.path, jdk.architecture)
});
}
/**
* Cheap fingerprint of the installation stored at a tool-cache path. The
* `<architecture>.complete` marker is (re)created by `tc.cacheDir` every time an
* installation is written, so its inode and timestamps change whenever the
* installation is replaced. This avoids rehashing a multi-hundred-megabyte JDK
* directory while still detecting that the bytes behind a key were swapped.
*/
function getInstallationIdentity(
jdkPath: string,
architecture: string
): string | undefined {
const architecturePath = path.join(jdkPath, architecture);
try {
const marker = fs.statSync(`${architecturePath}.complete`);
const installation = fs.statSync(architecturePath);
return [
marker.ino,
marker.mtimeMs,
marker.ctimeMs,
marker.size,
installation.ino,
installation.mtimeMs,
installation.ctimeMs
].join(':');
} catch {
return undefined;
}
}
export function getJdkVerificationIdentity(
verifySignature: boolean,
enforceSignatureVerification: boolean,
publicKey?: SignatureVerificationKey
): string {
if (!verifySignature) {
return 'disabled';
}
const verificationPolicy = enforceSignatureVerification
? 'enforced'
: 'check-and-warn';
if (!publicKey) {
return `${verificationPolicy}:bundled`;
}
const publicKeys = Array.isArray(publicKey) ? publicKey : [publicKey];
const normalizedKeys = publicKeys.map(key =>
key.replace(/\r\n?/g, '\n').trim()
);
const fingerprintSource = Array.isArray(publicKey)
? normalizedKeys.map(key => `${Buffer.byteLength(key)}:${key}`).join('')
: normalizedKeys[0];
const fingerprint = createHash('sha256')
.update(fingerprintSource)
.digest('hex');
return `${verificationPolicy}:custom:sha256:${fingerprint}`;
}
export async function saveJdkCaches(): Promise<void> {
const state = core.getState(STATE_JDK_CACHES);
if (!state) {
return;
}
const caches = parseJdkCacheState(state);
for (const jdk of caches) {
if (jdk.matchedKey === jdk.key) {
core.info(
`Cache hit occurred on the JDK primary key ${jdk.key}, not saving cache.`
);
continue;
}
if (!fs.existsSync(jdk.path)) {
core.debug(`JDK cache path does not exist, not saving: ${jdk.path}`);
continue;
}
if (!jdk.installation) {
core.debug(
`No JDK installation was registered for the key ${jdk.key}, not saving cache.`
);
continue;
}
if (
getInstallationIdentity(jdk.path, jdk.architecture) !== jdk.installation
) {
core.warning(
`The JDK installation in ${jdk.path} was replaced after it was registered for the key ${jdk.key}; not saving cache.`
);
continue;
}
try {
const cacheId = await cache.saveCache([jdk.path], jdk.key);
if (cacheId !== -1) {
core.info(`JDK cache saved with the key: ${jdk.key}`);
}
} catch (error) {
const err = error as Error;
if (err.name === cache.ReserveCacheError.name) {
core.info(err.message);
} else {
// Saving is best-effort and per entry: one failure must not suppress
// the remaining JDK caches.
core.warning(
`Failed to save the JDK cache with the key ${jdk.key}: ${err.message}`
);
}
}
}
}
export function buildJdkCacheKey(jdk: JdkCache): string {
const runnerOs = process.env['RUNNER_OS'] ?? process.platform;
const normalizedArchitecture = jdk.architecture.toLowerCase();
const identity = JSON.stringify({
keyVersion: JDK_CACHE_KEY_VERSION,
runnerOs,
distribution: jdk.distribution.toLowerCase(),
packageType: jdk.packageType.toLowerCase(),
architecture: normalizedArchitecture,
version: jdk.version,
source: jdk.source,
verification: jdk.verification
});
const digest = createHash('sha256').update(identity).digest('hex');
return `setup-java-jdk-v${JDK_CACHE_KEY_VERSION}-${runnerOs}-${normalizedArchitecture}-${digest}`;
}
function recordJdkCache(jdk: JdkCacheState): void {
const existing = restoredCaches.findIndex(
item => item.key === jdk.key && item.path === jdk.path
);
if (existing === -1) {
restoredCaches.push(jdk);
} else {
restoredCaches[existing] = {...restoredCaches[existing], ...jdk};
}
core.saveState(STATE_JDK_CACHES, JSON.stringify(restoredCaches));
}
function parseJdkCacheState(state: string): JdkCacheState[] {
const value: unknown = JSON.parse(state);
if (
!Array.isArray(value) ||
!value.every(
item =>
typeof item === 'object' &&
item !== null &&
typeof (item as JdkCacheState).key === 'string' &&
typeof (item as JdkCacheState).path === 'string' &&
typeof (item as JdkCacheState).architecture === 'string' &&
((item as JdkCacheState).matchedKey === undefined ||
typeof (item as JdkCacheState).matchedKey === 'string') &&
((item as JdkCacheState).installation === undefined ||
typeof (item as JdkCacheState).installation === 'string')
)
) {
throw new Error('Invalid JDK cache information retrieved from state.');
}
return value as JdkCacheState[];
}